Home > Back-end >  converting multiple text files into a single csv file with two columns
converting multiple text files into a single csv file with two columns

Time:08-16

I want to convert multiple text files(in same folder) into a single csv file with column1 as text files' name and column2 as text file's content.

I used the following code to copy the text file contents of text files to excel sheet.

import glob

filepaths=list(glob.glob(path "\*"))

for filepath in filepaths:
    with open("document.csv","a") as fd:
        fd.write(open(filepath,"r").read())

Please find the output in the image I attached. I want the text contents of all files to be in a single column and text file names to be in another column. I have little to no experience in file handling. Your help would be highly appreciated.

https://i.stack.imgur.com/Y8wWE.png

CodePudding user response:

Don't use standard open(), write() to create csv file but use standard module csv for this.

CSV uses , to separate columns, and new line to separate rows. You put text from file with , and new line and Excel treads them as separators - and you get text in many rows and columns.

But this needs to put all text in " " to escape these special chars (and Excel will treat them as normal chars in text. But this makes another problem because text may have own " which you would converted to \" - but module csv will do it all automatically.

import glob
import csv

filepaths = list(glob.glob(path "\*")) 

for filepath in filepaths:
    with open(filepath) as fd:
        text = fd.read()
    with open("document.csv", "a") as fd:
        writer = csv.writer(fd)
        writer.writerow( [filepath, text] )
  • Related