尝试使用os.path通过文件搜索创建CSV文件 [英] Trying to create a CSV file with a file search using os.path

查看:194
本文介绍了尝试使用os.path通过文件搜索创建CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to open the main folder containing all files (1), search though the files and only grab any .txt file with "mtn" in the title (2), print a the list of txt files (3) then list the txt files in a csv file, including their full path (4).

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

I can do (1) through (3) with my current code, however the CSV file that gets produced only contains the last filename, so I think there is something wrong with the order of my loops

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

In the console I get a running list of the filenames and the statement at the end with the 565 files found. The CSV file should have all of those files listed but only has the last one.

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

I tried indenting another for loop under the header:

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

但这也不起作用.

推荐答案

您正在w+模式下多次打开文件(解释为

You're opening the file multiple times in w+ mode (explained here in the documentation), which causes its contents to be truncated each time — so that's why you're only seeing the last one. You actually only need to open the file once, and then can write rows to it as needed.

这是我的意思:

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

这篇关于尝试使用os.path通过文件搜索创建CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆