Python 为什么';这个函数能抓取我的csv文件中的数据吗?
我试图简单地打开一个csv文件,并打印出该文件中的行。当我将文件作为字符串传递到此函数时,输出是字符串的内容,而不是文件的行Python 为什么';这个函数能抓取我的csv文件中的数据吗?,python,function,csv,Python,Function,Csv,我试图简单地打开一个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
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']
['_']
考虑到您发布的代码有错误,我认为您没有发布实际代码
\u print\u 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']
我发现您的代码甚至没有运行,因为语法错误,正如其他人指出的那样。另外,您不需要关闭文件: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')
您是否确保使用了正确的字段分隔符?另外,
open(filename,'rt')
更常见地被编写和理解为open(filename)
——而且,您不需要打开的文件.close()
,它将自动发生在块的末尾。。。(您实际上是在with块中关闭它,因此我希望对关闭的文件错误进行操作)如果您的代码有语法错误,则在读取文件=
行上不应该有:
。否则,你的代码对我来说很好。据我所知,代码在语法上甚至不有效。我认为这是获得单字符迭代的唯一方法。csv文件在换行符处断开行,但我相信它依赖于文件迭代器来完成断开。