我想打开包含所有文件的主文件夹(1),搜索所有文件,只抓取标题中带有“mtn”的任何.txt文件(2),打印txt文件列表(3),然后在csv文件中列出txt文件,包括其完整路径(4)
我可以使用当前代码执行(1)到(3),但是生成的CSV文件只包含最后一个文件名,因此我认为循环的顺序有问题
mtnpath = r"G:\somepath\"
num_files = 0
for root, dirs, files in os.walk(mtnpath):
for filename in files:
if fnmatch.fnmatch(filename, '*mtn*'):
num_files = num_files + 1
with open(mtnpath + "/" + "txt_file_list.csv", 'w+', newline='') as f:
thewriter = csv.writer(f)
# write the header row
thewriter.writerow(['Filename', 'Path', ])
# write the rest of the rows with files and path
thewriter.writerow([filename, 'Path', ])
print(filename)
print("The total number of mtn files found was " + str(num_files))
在控制台中,我得到一个文件名的运行列表,并在最后找到565个文件。CSV文件应列出所有这些文件,但仅列出最后一个
我尝试在标题下缩进另一个for
循环:
for filename in files:
thewriter.writerow([filename, 'Directory', ])
但这也不行
您在
w+
模式下多次打开文件(文档中解释了here),这会导致每次文件内容都被截断,因此您只能看到最后一个。实际上,您只需要打开文件一次,然后就可以根据需要向其中写入行我的意思是:
模式字符串
'w+'
导致任何现有内容被截断。也许再看python open built-in function: difference between modes a, a+, w, w+, and r+?无论如何,您都不想重复打开和关闭同一个文件;只需在主循环外打开一次,然后在有更多东西要写时再写
(切换到
'a'
而不是'w+'
将只需很少的更改就可以修复代码;但随后您会让操作系统进行大量的操作,以打开文件,查找到最后,然后针对您要编写的每一行再次关闭它。)相关问题 更多 >
编程相关推荐