在python中读取csv文件两次

问题描述:

这是我的Python代码:

Here is my Python code:

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()

我可以打印#查找订单employeeID = 5,shipCountry =巴西",但是对于#查找订单employeeID = 5我什么也没得到.我在想如何多次读取(选择)同一csv文件中的行.

I can print something of "# Find order employeeID=5, shipCountry="Brazil"", but I got nothing for # Find order employeeID=5. I was thinking of how to reading(selecting) rows in the same csv files more than one time.

您只是在读取CSV文件,但如果要多次处理数据,则应将内容读入变量.这样一来,您不必在每次需要处理文件时都重新读取该文件.

You're just reading right through your CSV file, but if you want to work on the data in multiple passes, you should read the contents into a variable. Then you don't have to re-read the file every time you need to do stuff with it.

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文件太大而无法容纳到内存中(或者由于某种原因您不想将其全部读取到内存中),那么您将需要一种不同的方法.如果需要,请发表评论.

If your CSV file is too huge to fit into memory (or you don't want to read it all into memory for some reason), then you'll need a different approach. If you need that, please leave a comment.