这是我的 Python 代码:
import csv
# Reading
ordersFile = open('orders.csv', 'rb')
ordersR = csv.reader(ordersFile, delimiter=',')
# Find order employeeID=5, shipCountry="Brazil"
print "Find order employeeID=5, shipCountry=\"Brazil\""
for order in ordersR:
if order[2] == '5' and order[13] == 'Brazil':
print order
# Find order employeeID=5
print "Find order employeeID=5"
for order in ordersR:
if order[2] == '5':
print order
ordersFile.close()
我可以打印“# Find order employeeID=5, shipCountry="Brazil"”的内容,但对于#Find order employeeID=5 我什么也得不到。我在考虑如何多次读取(选择)同一个 csv 文件中的行。
最佳答案
您只是直接阅读 CSV 文件,但如果您想分多次处理数据,则应将内容读入变量。这样您就不必在每次需要处理文件时都重新读取文件。
import csv
# Read order rows into our list
# Here I use a context manager so that the file is automatically
# closed upon exit
with open('orders.csv') as orders_file:
reader = csv.reader(orders_file, delimiter=',')
orders = list(reader)
# Find order employeeID=5, shipCountry="Brazil"
print "Find order employeeID=5, shipCountry=\"Brazil\""
for order in orders:
if order[2] == '5' and order[13] == 'Brazil':
print order
# Find order employeeID=5
print "Find order employeeID=5"
for order in orders:
if order[2] == '5':
print order
如果您的 CSV 文件太大而无法放入内存(或者出于某种原因您不想将其全部读入内存),那么您将需要一种不同的方法。如果您需要,请发表评论。
关于python - 在python中读取csv文件两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46083510/