将单个行及其列的值存储到 python 中的不同变量中

store the values of a single row and its columns into different variables in python

我想将单行及其列的值存储到不同的变量中。但是不知道可不可以。

这里贴出我的代码,请看一下

import csv

csvFile = csv.reader(open("D:\Sikuli\example1.csv", "rU"))
mycsv = [] # empty list

for row in csvFile:
    mycsv.append(row)
    print row
    print "....."
    print row[1]

在这种情况下,我只能打印行,无法将数据存储到不同的变量中。请给我解决方案。 提前谢谢你

我的 csv 文件是:

Presedence,Sno,STP-testcaseno,Test_id,Scenario,Simulator,Comport
0,1,STP-GPSBL-001,SimZen-001,general,SimZen,com1
1,2,STP-GPSBL-002,SimZen-002,general,SimZen,com2
1,3,STP-GPSBL-003,Simplex-003,gpsblhsiura1,Simplex,com1
0,4,STP-GPSBL-004,SimZen-004,gpsblhsiura1,SimZen,com1
1,5,STP-GPSBL-005,Accord-005,general1,Accord,com3
0,6,STP-GPSBL-006,Ifen-006,general1,Ifen,com1

我举例说明:

eggs.csv没有header name

0@mailinator.com,0fname,0lname,0place
1@mailinator.com,1fname,1lname,1place
2@mailinator.com,2fname,2lname,2place
3@mailinator.com,3fname,3lname,3place

然后

import csv
with open('eggs.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')
    for i in spamreader:
        print i # you can append this to your list

>>>['10@mailinator.com', '10fname', '10lname', '10place']
   ['11@mailinator.com', '11fname', '11lname', '11place']
   ...

如果您在 eggs.csv 中有 header,例如:

email,firstname,lastname,place
0@mailinator.com,0fname,0lname,0place
1@mailinator.com,1fname,1lname,1place
2@mailinator.com,2fname,2lname,2place
3@mailinator.com,3fname,3lname,3place

那你可以用DictReader喜欢

with open('eggs.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row) #you can append this

>>>{'lastname': '0lname', 'place': '0place', 'email': '0@mailinator.com', 'firstname': '0fname'}
   {'lastname': '1lname', 'place': '1place', 'email': '1@mailinator.com', 'firstname': '1fname'}
   ...

注意

我将 , 用作 delimiter,因为值在 eggs.csv

中用 , 分隔

你可以这样做

import csv

csvFile = csv.reader(open("D:\Sikuli\example1.csv", "rU"))
mycsv = {} # empty dictionary

for row in csvFile:
    mycsv["col_field_name1"] = row[1]
    mycsv["col_field_name2"] = row[2]
    ...

这里还有其他关于从 csv 文件创建字典的示例 Creating a dictionary from a csv file?

使用csv.DictReader并快乐

import csv

with open("D:\Sikuli\example1.csv") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['Presedence'], row['Sno'], row['STP-testcaseno'])

0 1 STP-GPSBL-001
1 2 STP-GPSBL-002
1 3 STP-GPSBL-003
...

关于按值过滤评论中的问题。

for row in reader:
    if row['Presedence'] == 'Some Value':
        print(row['Presedence'], row['Sno'], row['STP-testcaseno'])
    else:
        print(row['Sno'], row['STP-testcaseno'])