Python TypeError:预期的str,字节或os.PathLike对象,而不是_io.TextIOWrapper

时间:2020-03-16 11:55:51

标签: python csv typeerror

我试图将以竖线分隔的文本文件转换为CSV文件,然后遍历并打印CSV文件。这是我的代码:

from datetime import timedelta

prev_month_15 = (this_month_15 - timedelta(days=15)).replace(day=15)

但是,我收到此错误消息:


with open("...somefile.txt", "r") as text_file:
    text_reader = csv.reader(text_file, delimiter='|')
    with open("...somefile.csv", 'w') as csv_file:
        csv_writer = csv.writer(csv_file, delimiter=',')
        csv_writer.writerows(text_reader)

with open (csv_file, 'r') as f:
    reader = csv.reader (f, delimiter=',')
    for row in reader:
        print(row)

任何人都可以解释这意味着什么吗?

此外,如果我要将此功能用作函数,如何输入文件名作为输入,然后更改该文件以添加.csv扩展名(转换为csv文件)?

谢谢

2 个答案:

答案 0 :(得分:3)

您要传递open一个已经打开的文件,而不是您创建的文件的路径。

替换:

with open (csv_file, 'r') as f:

with open ("...somefile.csv", 'r') as f:

要更改功能中的扩展名,请执行以下操作:

import pathlib

def txt_to_csv(fname):
    new_name = f'{Path(fname).stem}.csv'

    with open(fname, "r") as text_file:
        text_reader = csv.reader(text_file, delimiter='|')
        with open(new_name, 'w') as csv_file:
            csv_writer = csv.writer(csv_file, delimiter=',')
            csv_writer.writerows(text_reader)

    with open (new_name, 'r') as f:
        reader = csv.reader (f, delimiter=',')
        for row in reader:
            print(row)

答案 1 :(得分:1)

我不是csv库的专家。但是,关于您的其他问题:

此外,如果我要将此功能用作函数,如何输入文件名作为输入,然后更改该文件以添加.csv扩展名(转换为csv文件)?

解决方案:

def converter(input_file_name):
  with open(input_file_name, 'r') as txt_file:
    output_file_name = input_file_name.replace('.txt', '.csv')
    with open(output_file_name, 'w') as csv_file:
      # your logic resides here.