简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM