1

我试图简单地打开一个 csv 文件,并打印出该文件中的行。当我将文件作为字符串传递给此函数时,输出是字符串的内容,而不是文件的行。

def _print_rows(filename):
    with open(filename, 'rt') as opened_file:
        read_file = csv.reader(opened_file):
            for row in read_file:
                print row
                raw_input()
        opened_file.close()

>>> module_name._print_rows('first_class_profile.csv')  
['f']

['i']

['r']

['s']

['t']

['_']
4

2 回答 2

3

考虑到您发布的代码有错误,我认为您没有发布实际代码。

您的_print_rows函数实际上是打印文件名中的字符,而不是文件的内容。如果您将 csv 文件的文件名传递给csv.reader而不是打开的文件,则会发生这种情况:

>>> import csv
>>> filename = 'first_class_profile.csv'
>>> reader = csv.reader(filename) # whoops! should have passed opened_file
>>> for row in reader:
...     print row
...
['f']
['i']
['r']
['s']
['t']
['_']
['c']
['l']
['a']
['s']
['s']
['_']
['p']
['r']
['o']
['f']
['i']
['l']
['e']
['.']
['c']
['s']
['v']
于 2012-11-21T22:19:10.590 回答
0

正如其他人指出的那样,由于语法错误,我发现您的代码甚至没有运行。此外,您不需要关闭文件:with 语句会处理此问题。在我修改了您的代码后,它似乎可以工作:

import csv
def _print_rows(filename):
    with open(filename, 'rt') as opened_file:
        read_file = csv.reader(opened_file)
        for row in read_file:
            print row
            raw_input()

_print_rows('first_class_profile.csv')
于 2012-11-21T22:31:36.743 回答