多次打开csv.reader

时间:2018-04-23 10:32:56

标签: python-3.x csv

我正在尝试在同一个函数中打开两次csv.reader。 我使用了2个“with”块并以不同方式命名变量:

def make_template(input_file):

import csv

with open(input_file,'rt') as input_file:        
    reader = csv.reader(input_file, delimiter='\t')
    ## code    

with open(input_file,'rt') as inputf, open('template.csv','w') as final:
    writer = csv.writer(final, delimiter='\t')
    reader1 = csv.reader(inputf, delimiter='\t')
    ## code

我收到了错误 -

TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper

我做错了什么?

由于 希拉

1 个答案:

答案 0 :(得分:3)

你的问题就在这一行

with open(input_file, 'rt') as inputf:

因为它用文件对象覆盖input_file,所以后者 open获取文件对象作为输入,而不是字符串。

这将解决您的问题:

import csv

with open(input_file,'rt') as in_file:
    reader = csv.reader(in_file, delimiter='\t')
    ## code

with open(input_file,'rt') as inputf, open('template.csv','w') as final:
    writer = csv.writer(final, delimiter='\t')
    reader1 = csv.reader(inputf, delimiter='\t')
    ## code

作为一般规则,我喜欢从文件对象的概念中分离文件名的概念。这避免了这些问题,并且可以说更具可读性。 所以我建议使用以下变量命名:

import csv

with open(input_filename,'rt') as input_file:
    reader = csv.reader(input_file, delimiter='\t')
    ## code

with open(input_filename,'rt') as input_file, open('template.csv','w') as final:
    writer = csv.writer(final, delimiter='\t')
    reader1 = csv.reader(input_file, delimiter='\t')
    ## code