Ala*_*ith 13
用于list一次性抓取所有行作为列表。然后通过列表中的索引/偏移量访问目标行。例如:
#!/usr/bin/env python
import csv
with open('source.csv') as csv_file:
csv_reader = csv.reader(csv_file)
rows = list(csv_reader)
print(rows[8])
print(rows[22])
Run Code Online (Sandbox Code Playgroud)
ch3*_*3ka 11
您可以使用a list comprehension来过滤文件,如下所示:
with open('file.csv') as fd:
reader=csv.reader(fd)
interestingrows=[row for idx, row in enumerate(reader) if idx in (28,62)]
# now interestingrows contains the 28th and the 62th row after the header
Run Code Online (Sandbox Code Playgroud)
您只需跳过必要的行数:
with open("test.csv", "rb") as infile:
r = csv.reader(infile):
for i in range(8): # count from 0 to 7
next(r) # and discard the rows
row = next(r) # "row" contains row number 9 now
Run Code Online (Sandbox Code Playgroud)
您可以阅读所有这些,然后使用普通列表来查找它们。
with open('bigfile.csv','rb') as longishfile:
reader=csv.reader(longishfile)
rows=[r for r in reader]
print row[9]
print row[88]
Run Code Online (Sandbox Code Playgroud)
如果您有一个大文件,这可能会耗尽您的内存,但如果文件少于 10,000 行,您就不应该遇到任何大的减速。
| 归档时间: |
|
| 查看次数: |
34532 次 |
| 最近记录: |