Python Forum
Output CSV file with filepath and file contents - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Output CSV file with filepath and file contents (/thread-28777.html)



Output CSV file with filepath and file contents - glittergirl - Aug-03-2020

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



RE: Output CSV file with filepath and file contents - glittergirl - Aug-03-2020

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