简体   繁体   中英

How to convert all the txt file from a dir to csv's (creating and writing to file )and save them using Python?

convert all txt files delimiter '|' from dir path and convert to csv and save in a location using python?

i have tried this code which is hardcoded.

import csv

txt_file = r"SentiWS_v1.8c_Positive.txt"
csv_file = r"NewProcessedDoc.csv"

with open(txt_file, "r") as in_text:
    in_reader = csv.reader(in_text, delimiter = '|')
    with open(csv_file, "w") as out_csv:
        out_writer = csv.writer(out_csv, newline='')
        for row in in_reader:
            out_writer.writerow(row)

Expecting csv files with same file names in dir path for all txt files in path location

pathlib provides most of the file handling stuff for you:

import csv, pathlib

for path in pathlib.Path(".").glob("*.txt"):
    with path.open() as txtfile, path.with_suffix(".csv").open(mode="w") as csvfile:
        reader = csv.reader(txtfile, delimiter = '|')
        writer = csv.writer(csvfile)
        for row in reader:
            writer.writerow(row)

TO avoid blanks in the output file just added newline parameter in the above code import csv, pathlib

for path in pathlib.Path(".").glob("*.txt"):
    with path.open() as txtfile, path.with_suffix(".csv").open(mode="w",**newline=''**) as csvfile:
        reader = csv.reader(txtfile, delimiter = '|')
        writer = csv.writer(csvfile)
        for row in reader:
            writer.writerow(row)

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