将列表写入文件

时间:2014-10-22 17:02:13

标签: python list text-files

我有一个.tif个文件夹,我想使用python将他们的文件名写入.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

1 个答案:

答案 0 :(得分:7)

您忘记在程序结束时实际调用close方法。在其后添加()来执行此操作:

target.close()

在某些系统(可能是您的系统)上,您必须关闭该文件以提交更改。


或者,更好的是,您可以使用with-statement打开文件,该文件会自动关闭它:

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