2014-06-27 5 views
-4

다른 기준에 따라 폴더 내의 파일 이름을 바꿀 작은 스크립트를 작성 중입니다. 내가 이것을 사용하려고하지만 폴더에이 점파일 이름에 따라 파이썬의 파일 이름 바꾸기

f = [] 
for file in os.walk(outputfolder): 
    f.append(file) 

에 붙어있다 (C : \ 폴더) 나는이 개 파일이 : file1.csv, file2.csv

난을 만드는 방법 각 파일에 대해 같은

if(file1.csv.find(1) > 0) 
    do this 
else 
    do this 

감사합니다 뭔가를 폴더 안에 가서 할 루프는 내가 잠시 동안 노력 해왔다와 나는 해결책을 찾을 수 없습니다

+0

파일의 * 내용 *에서 '1'을 찾으시겠습니까? 제 튜토리얼 (https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files)을 읽어야합니다. – jonrsharpe

답변

0
for root, dirs, files in os.walk("path/to/folder"): 
    for filename in files: 
     if "1" in filename: 
      do_something() 
     else: 
      do_something_else() 

os.walk을 사용하면 디렉토리 트리의 생성자를 반환합니다. 같은 테스트 디렉토리를 상상해

C:\temp 
| \subdir 
| | subfile1.txt 
| | subfile2.txt 
| file1.txt 
| file2.txt 

list(os.walk) 생산됩니다

말을하는 것입니다
[("C:\\temp", ["subdir"], ["file1.txt","file2.txt"]), 
("C:\\temp\\subdir", [], ["subfile1.txt","subfile2.txt"])] 

는, 각각의 반복은 원래 인수의 각 하위 디렉토리에 대한 root, list_of_directories_in_root, list_of_files_in_root을 생산하고 있습니다. 당신이 정말로 root 또는 dirs 걱정하지 않는다, 그러나 당신이 파일의 이름을 변경 (또는 등) 경우 적어도 필요합니다

for root, dirs, files in os.walk("path/to/folder"): 

가 지금은 사실이다 : 따라서 우리는 os.walk에 걸쳐 같은 방법으로 반복 os.rename(os.path.join(root, filename), "newname.txt")을 수행 할 것이므로 root입니다.

1

중첩 된 디렉토리를보고 싶지 않으면 과장입니다. os.listdir은 덜 복잡합니다.

파일 이름이나 파일 내용을 조작하려면 질문이 모호합니다. 그래서 나는 아래 둘 모두를 제공합니다. :

import os 

outputfolder = "/home/jack/code/tests" 

for filename in os.listdir(outputfolder): 
    # just the filename 
    print filename 
    if "1" in filename: 
     print "\t1 is in the filename %s" % (filename) 

    # the file contents 
    file_path = os.path.join(outputfolder, filename) 
    with open(file_path) as f: 
     file_contents = f.read() 
     if "1" in file_contents: 
      print "\t1 is in the contents of %s" % (filename) 

    print "---"