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

前端 未结 2 1056
栀梦
栀梦 2021-01-16 11:18

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)

2条回答
  •  花落未央
    2021-01-16 11:34

    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.

    Here's what I mean:

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

提交回复
热议问题