我试图简单地打开一个 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']
['_']
最佳答案
考虑到您发布的代码有错误,我认为您没有发布实际的代码。
您的_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']
关于python - 为什么这个函数不抓取我的 csv 文件中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13502909/