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
  How to write variable in a python file then import it in another python file? tatahuft 4 2,202 Jan-01-2025, 12:18 AM
Last Post: Skaperen
  JSON File - extract only the data in a nested array for CSV file shwfgd 2 2,210 Aug-26-2024, 10:14 PM
Last Post: shwfgd
  FileNotFoundError: [Errno 2] No such file or directory although the file exists Arnibandyo 0 2,657 Aug-12-2024, 09:11 AM
Last Post: Arnibandyo
  "[Errno 2] No such file or directory" (.py file) IbrahimBennani 13 13,983 Jun-17-2024, 12:26 AM
Last Post: AdamHensley
  Connecting to Remote Server to read contents of a file ChaitanyaSharma 1 4,739 May-03-2024, 07:23 AM
Last Post: Pedroski55
  Can rich.logging output to file? pyfoo 1 4,258 Mar-21-2024, 10:30 AM
Last Post: pyfoo
  file open "file not found error" shanoger 8 16,026 Dec-14-2023, 08:03 AM
Last Post: shanoger
  Need to replace a string with a file (HTML file) tester_V 1 2,946 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 2,929 Jul-17-2023, 10:15 PM
Last Post: Pedroski55
  How to "tee" (=split) output to screen and into file? pstein 6 6,039 Jun-24-2023, 08:00 AM
Last Post: Gribouillis

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.