[英]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 '|'转换所有 txt 文件分隔符 '|' from dir path and convert to csv and save in a location using python?
从目录路径转换为 csv 并使用 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对于路径位置中的所有 txt 文件,在 dir 路径中需要具有相同文件名的 csv 文件
pathlib provides most of the file handling stuff for you: pathlib为您提供了大部分文件处理内容:
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为了避免输出文件中的空白,在上面的代码中添加了换行符参数 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.