将列表写入文件

-2 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
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 7

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

target.close()
Run Code Online (Sandbox Code Playgroud)

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


或者,更好的是,您可以使用with语句打开文件,该文件将自动为您关闭它:

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