2014-10-22 2 views
-2

나는 .tif 개의 파일을 가지고 있는데, 나는 파일 이름을 .txt 또는 .csv에 파이썬을 사용하여 파일 확장자없이 쓰고 싶다. 이것은 꽤 간단해야하지만 어떤 이유로 나는 항상 빈 텍스트 파일로 끝납니다. 누구든지 내 코드에서 내가 잘못하고있는 것을 볼 수 있습니까? .rstrip 명령에 문제가 없다는 것을 알기 때문에 이름을 올바르게 인쇄합니다.목록을 파일로 저장

# import os so you get the os access methods 
import os 

# set a directory the files are in 
workingDir = r'F:\filepath\files' 

# get a list of all the files in the directory 
names = os.listdir(workingDir) 

#print file names 
for name in names: 
    listname=name.rstrip('.tif') 
    print listname 


#write filenames to text file 
target = open("F:\filepath\list.txt", "w") 

for name in names: 
    listname=name.rstrip('.tif') 
    target.writelines(listname) 
    target.writelines("\n") 

target.close 

답변

7

실제로 프로그램을 마치면 close 메서드를 호출하는 것을 잊었습니다. 그것은이 작업을 수행 한 후 ()를 추가

target.close() 

을 일부 시스템에서 (아마도 당신), 당신은 변경 사항을 적용 할 파일을 닫아야합니다.

with open("F:\filepath\list.txt", "w") as target: 
    for name in names: 
     listname=name.rstrip('.tif') 
     target.writelines(listname) 
     target.writelines("\n") 
:


또는, 더 나은, 당신은 자동으로 당신을 위해 그것을 닫습니다 파일을 열려면 with-statement을 사용할 수 있습니다