【发布时间】:2010-09-30 17:05:43
【问题描述】:
当我使用 csv.reader 浏览文件时,如何返回文件顶部。如果我使用普通文件执行此操作,我可以执行“file.seek(0)”之类的操作。 csv 模块有类似的东西吗?
提前谢谢;)
【问题讨论】:
当我使用 csv.reader 浏览文件时,如何返回文件顶部。如果我使用普通文件执行此操作,我可以执行“file.seek(0)”之类的操作。 csv 模块有类似的东西吗?
提前谢谢;)
【问题讨论】:
您仍然可以使用 file.seek(0)。例如,请看以下内容:
import csv
file_handle = open("somefile.csv", "r")
reader = csv.reader(file_handle)
# Do stuff with reader
file_handle.seek(0)
# Do more stuff with reader as it is back at the beginning now
这应该可以工作,因为 csv.reader 正在使用它。
【讨论】:
您可以直接查找文件。例如:
>>> f = open("csv.txt")
>>> c = csv.reader(f)
>>> for row in c: print row
['1', '2', '3']
['4', '5', '6']
>>> f.seek(0)
>>> for row in c: print row # again
['1', '2', '3']
['4', '5', '6']
【讨论】:
csv_aggregate(reader, agg_functions, reset_after_calc=True) 我们可以使用reader._file.seek(0) 或类似的东西吗?
csv_reader = csv.reader(stdout.decode('ascii').split('\n'), delimiter=' ')
我发现csv.reader 和csv.DictReader 有点难以使用,因为当前的line_num。 making a list 从第一次读取效果很好:
>>> import csv
>>> f = open('csv.txt')
>>> lines = list( csv.reader(f) ) # <-- list from csvReader
>>>
>>> for line in lines:
... print(line)
['1', '2', '3']
['4', '5', '6']
>>>
>>> for line in lines:
... print(line)
['1', '2', '3']
['4', '5', '6']
>>>
>>>lines[1]
['4', '5', '6']
这会捕获dictReader 使用的optional first row,但可以让您一次又一次地使用列表,甚至检查单个行。
【讨论】: