繁体   English   中英

在 Python 中将管道分隔的文本文件文件夹转换为 CSV

[英]Convert a folder of pipe-delimited text files to CSV in Python

我有一个包含“|”的 .txt 文件文件夹而不是逗号,我正在尝试将其转换为 CSV 格式。 我发现了一些应该可以工作的代码,但是我不断收到错误消息“迭代器应该返回字符串,而不是字节(您是否以文本模式打开文件?)”。 我发现的代码没有嵌套在for循环中,这可能是问题所在吗?

编码:

import csv
import os

folder_path= r'C:\Users\%user%\Documents\data\Dataset'
txt_files = os.listdir(folder_path)

to_csv = []

for file in range(0, len(txt_files)):
    path_name = os.path.abspath(os.path.join(folder_path, txt_files[file]))
    to_csv.append(path_name)

for file in to_csv:
    with open(file, "rb") as f:
        with_pipes = csv.reader(f, delimiter='|')
        wo_pipes = list(with_pipes)

将 open 语句更改为:

with open(file, "r", encoding="utf-8") as f:

这将以文本模式打开文件,而不是二进制模式,并且编码允许您读取非 ASCII 内容

with open(output_file_name, 'w') as f_out:
    for line in source_lines:
        # get the count of delimiters in a line
        pipe_cnt = line.count('|')
        # replacing the delimiters in the line bases on count from previous step
        line = line.replace('|', ',', pipe_cnt)
        f_out.write(line)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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