繁体   English   中英

尝试使用 os.path 使用文件搜索创建 CSV 文件

[英]Trying to create a CSV file with a file search using os.path

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

我可以用我当前的代码做(1)到(3),但是生成的 CSV 文件只包含最后一个文件名,所以我认为我的循环顺序有问题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 文件应该列出了所有这些文件,但只有最后一个。

2

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

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

但这也不起作用。

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

这就是我的意思:

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))

模式字符串'w+'会导致任何现有内容被截断。 或许可以进一步查看python open built-in function: difference between mode a, a+, w, w+, and r+?

无论如何,您不想重复打开和关闭同一个文件; 只需在主循环打开它一次,然后在有更多要写的时候再写。

(切换到'a'而不是'w+'会以最小的更改修复您的代码;但随后您会导致操作系统执行大量操作来打开文件,寻找到最后,然后再次关闭它你想写的行。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM