kevin kevin - 4 months ago 11
Python Question

Convert txt files in a folder to rows in csv file

I have 100 txt files in a folder. I would like to create a csv file in which the content of each text file becomes a single row (actually, a single cell in a row) in this csv file. So, the result would be a csv file with 100 rows.

I tried the following code:

import glob

read_files = glob.glob('neg/*')

with open("neg.csv", "wb") as outfile:
for f in read_files:
with open(f, "rb") as infile:
for line in infile:
outfile.write(line)


This create a csv with over thousands of rows since each txt file contains multiple paragraphs. Any suggestion?

Answer

Try:

import glob
import csv

read_files = glob.glob('neg/*')

with open("neg.csv", "wb") as outfile:
    w=csv.writer(outfile)
    for f in read_files:
        with open(f, "rb") as infile:
            w.writerow([line for line in infile])

That makes each line a cell in the output and each file a row.

If you want each cell to be the entire contents of the file, try:

import glob
import csv

read_files = glob.glob('neg/*')

with open("neg.csv", "wb") as outfile:
    w=csv.writer(outfile)
    for f in read_files:
        with open(f, "rb") as infile:
            w.writerow(" ".join([line for line in infile]))