繁体   English   中英

如何将所有 txt 文件从目录转换为 csv(创建和写入文件)并使用 Python 保存它们?

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

转换所有 txt 文件分隔符 '|' 从目录路径转换为 ​​csv 并使用 python 保存在一个位置?

我试过这个硬编码的代码。

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)

对于路径位置中的所有 txt 文件,在 dir 路径中需要具有相同文件名的 csv 文件

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)

为了避免输出文件中的空白,在上面的代码中添加了换行符参数 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.

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