Python Forum
Output CSV file with filepath and file contents
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Output CSV file with filepath and file contents
#1
I want to output a CSV file with the filepath and file content in the directory. I tried the following code, but it only iterates through files in the folder. I want it to iterate through the entire directory, including subdirectories:

import csv
from pathlib import Path

with open('big.csv', 'w', encoding='Latin-1') as out_file:
    csv_out = csv.writer(out_file)
    csv_out.writerow(['FileName', 'Content'])
    for fileName in Path('.').resolve().glob('*.txt'):
        lines = [ ]
        with open(str(fileName.absolute()),'rb') as one_text:
            for line in one_text.readlines():
                lines.append(line.decode(encoding='Latin-1',errors='ignore').strip())
        csv_out.writerow([str(fileName),' '.join(lines)])
Reply
#2
After some googling, this is the correct answer:

import csv
from pathlib import Path
 
with open('big.csv', 'w', encoding='Latin-1') as out_file:
    csv_out = csv.writer(out_file)
    csv_out.writerow(['FileName', 'Content'])
    for fileName in Path('.').resolve().glob('**/*.txt'):
        lines = [ ]
        with open(str(fileName.absolute()),'rb') as one_text:
            for line in one_text.readlines():
                lines.append(line.decode(encoding='Latin-1',errors='ignore').strip())
        csv_out.writerow([str(fileName),' '.join(lines)])
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Can rich.logging output to file? pyfoo 1 185 Mar-21-2024, 10:30 AM
Last Post: pyfoo
  file open "file not found error" shanoger 8 942 Dec-14-2023, 08:03 AM
Last Post: shanoger
  Need to replace a string with a file (HTML file) tester_V 1 699 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  How can I change the uuid name of a file to his original file? MaddoxMB 2 868 Jul-17-2023, 10:15 PM
Last Post: Pedroski55
  How to "tee" (=split) output to screen and into file? pstein 6 1,289 Jun-24-2023, 08:00 AM
Last Post: Gribouillis
  output provide the filename along with the input file processed. arjunaram 1 903 Apr-13-2023, 08:15 PM
Last Post: menator01
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,046 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,063 Dec-15-2022, 04:32 PM
Last Post: Larz60+
Photo Making Zip file of a file and Directory Nasir 2 984 Oct-07-2022, 02:01 PM
Last Post: Nasir
  Need Help: Convert .pcl file to .pdf file ManuRaval 6 2,473 Sep-13-2022, 01:31 PM
Last Post: ManuRaval

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020