kevin
kevin

Reputation: 2014

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?

Upvotes: 0

Views: 1300

Answers (2)

dawg
dawg

Reputation: 104111

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

Upvotes: 2

honi
honi

Reputation: 968

Before writing each line, first do line.replace('\n',' ') to replace all new line characters with spaces.

Obviously, adjust your newline character according to your OS.

Upvotes: 0

Related Questions