为什么这个函数没有抓取我的csv文件中的数据?

时间:2012-11-21 22:12:16

标签: 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
                raw_input()
        opened_file.close()

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

['i']

['r']

['s']

['t']

['_']

2 个答案:

答案 0 :(得分: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']

答案 1 :(得分: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')