python - 尝试使用 os.path 通过文件搜索创建 CSV 文件

标签 python csv os.walk

我想打开包含所有文件的主文件夹 (1),搜索文件并仅抓取标题中包含“mtn”的任何 .txt 文件 (2),然后打印 txt 文件列表 (3)列出 csv 文件中的 txt 文件,包括其完整路径 (4)。

我可以用我当前的代码执行(1)到(3),但是生成的 CSV 文件仅包含最后一个文件名,所以我认为我的循环顺序有问题 CSV file

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 文件应该列出所有这些文件,但只有最后一个。

2

我尝试在标题下缩进另一个 for 循环:

    for filename in files:
        thewriter.writerow([filename, 'Directory', ])

但这也不起作用。

最佳答案

您在 w+ 模式下多次打开文件(在文档中解释 here),这会导致其内容每次都被截断 - 所以这就是为什么您只看到最后一个。实际上,您只需要打开该文件一次,然后就可以根据需要向其中写入行。

这就是我的意思:

import csv
import fnmatch
import os

mtn_path = r'G:\somepath'
pattern = '*mtn*'
txt_file_csv_path = os.path.join(mtn_path, 'txt_file_list.csv')

with open(txt_file_csv_path, 'w+', newline='') as f:
    thewriter = csv.writer(f)
    # Write a header row.
    thewriter.writerow(['Filename', 'Path', ])
    num_files = 0

    for root, dirs, files in os.walk(mtn_path):
        for filename in files:
            if fnmatch.fnmatch(filename, pattern):
                num_files += 1
                thewriter.writerow((filename, os.path.join(root, filename)))
                print(filename)

print('The total number of mtn files found was ' + str(num_files))

关于python - 尝试使用 os.path 通过文件搜索创建 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59954363/

相关文章:

python - Tornado 路由到 "base"处理程序

python - Numpy 选择不沿特定维度替换

Python 正则表达式搜索数字范围

python - os.walk 正则表达式

python - 我设置了 True=False 并且我无法撤消它

python - csv.writer.writerows 列表中缺少行

c# - 使用 FileHelper 格式化属性

python - ValueError 尝试遍历

python - 在 python 中使用 os.walk 更改目录

python - os.walk 还是 glob 更快?