2012-08-30 2 views
11

문제점은 다음과 같습니다. 내 디렉토리와 하위 디렉토리에있는 모든 파일 이름을 나열하고 그 출력을 txt 파일로 출력하려고합니다. 지금이 내가 지금까지 가지고있는 코드 :Python : 디렉토리와 하위 디렉토리에있는 모든 파일 이름을 나열한 다음 결과를 txt 파일에 인쇄하십시오.

import os 

for path, subdirs, files in os.walk('\Users\user\Desktop\Test_Py'): 
    for filename in files: 
    f = os.path.join(path, filename) 
    a = open("output.txt", "w") 
    a.write(str(f)) 

이 폴더에있는 파일의 이름을 나열 (6가)하지만, 각각의 새로운 파일은 이전이 때문에 출력에 하나의 파일 이름이 덮어 씁니다. txt 파일을 열 수 있습니다. 이 코드를 변경하여 output.txt 파일에 모든 파일 이름을 쓰도록하려면 어떻게해야합니까?

+3

루프 외부에서'open' 명령을 이동하십시오. – mgilson

+0

SO 검색을 수행 했습니까? 얼마 전부터 이것에 대한 정확한 복제물을 읽었을뿐입니다 ... –

답변

24

for 루프에서 파일을 열지 마십시오. 당신의 for 루프 전에 열이

import os 

a = open("output.txt", "w") 
for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'): 
    for filename in files: 
    f = os.path.join(path, filename) 
    a.write(str(f) + os.linesep) 

또는 컨텍스트 관리자 (더 좋은 연습입니다)를 사용하여 같은

: 단지에서 파일 이름 당신이 작성하는 코드 아래 사용할 수 있습니다

import os 

with open("output.txt", "w") as a: 
    for path, subdirs, files in os.walk(r'C:\Users\user\Desktop\Test_Py'): 
     for filename in files: 
     f = os.path.join(path, filename) 
     a.write(str(f) + os.linesep) 
+5

그리고'with' 문을 사용하여 파일을 열어야합니다. 그러면 루프가 끝날 때 파일이 자동으로 닫힙니다. –

+2

***을 사용하는 것이 더 좋습니다 *** 열린 파일은 프로세스를 완료 한 후 닫힙니다. 즉, "열기 ("output.txt ","w ")를" –

+0

@brain buck 편집 덕분에 – gefei

5

쓰기 모드에서 파일을 여는 중입니다. 추가 모드가 필요합니다. 자세한 내용은 manual을 참조하십시오.

변화

a = open("output.txt", "w") 

a = open("output.txt", "a") 
2

을 폴더.

import os 

a = open("output.txt", "w") 
for path, subdirs, files in os.walk(r'C:\temp'): 
    for filename in files: 
     a.write(filename + os.linesep) 
관련 문제