伙计们,希望得到关于处理以下任务的最佳方式的建议:
1.从CSV文件中读取数据。
2.根据步骤1中读取的数据编辑XML文件。
我是一个Python noob。到目前为止,我能够从CSV文件中读取数据。在我的Java世界中,我只是将“读取”数据传递给方法,然后迭代并编辑该方法中的XML文件。
我可以在Python中做类似的事情吗?在Python中是否有更高效,更清晰的方法来实现相同的目标?
import csv
ifile = open('my-file.csv', "rb")
reader = csv.reader(ifile)
rownum = 0
for row in reader:
#print row
if rownum == 0:
header = row
else:
colnum = 0
name = row[1]
desig = row[5]
print("Name: ", name)
print("Designation: ", desig)
rownum += 1
if rownum == 10:
break
ifile.close()
答案 0 :(得分:2)
你的问题有点清晰(你正在寻找的是什么)。 无论如何,根据我的理解,您正在寻找一种简单的方法来阅读 csv 文件并打印 ith 特定格式的列(例如名称:...)。 我假设您的文件如下所示:
blah,Name,blahblah,blahblahblah,blahblahblahblah,Designation
whatever,name1,whatever,whatever,whatever,Designation1
whatever,name2,whatever,whatever,whatever,Designation2
whatever,name3,whatever,whatever,whatever,Designation3
whatever,name4,whatever,whatever,whatever,Designation4
whatever,name5,whatever,whatever,whatever,Designation5
whatever,name6,whatever,whatever,whatever,Designation6
如果是这样的话,那就是我要做的。我会使用已知的pandas库
import pandas as pd
将csv文件读入数据框" df"
df = pd.read_csv('my-file.csv')
变量头将保存列名
header = list(df) # the equivilant of your "row[0]" variable
打印所需数据的方法#1
for i, j in zip(list(df['Name'].values), list(df['Designation'].values)):
print "Name: {} \nDesignation: {}".format(i, j)
这打印出以下内容:
Name: name1
Designation: Designation1
Name: name2
Designation: Designation2
Name: name3
Designation: Designation3
Name: name4
Designation: Designation4
Name: name5
Designation: Designation5
Name: name6
Designation: Designation6
打印所需数据的方法#2
df['Name'] = df['Name'].map('Name: {}'.format)
df['Designation'] = df['Designation'].map('Designation: {}'.format)
print df[['Name', 'Designation']].head(n=10)
将打印出以下内容:
0 Name: name1 Designation: Designation1
1 Name: name2 Designation: Designation2
2 Name: name3 Designation: Designation3
3 Name: name4 Designation: Designation4
4 Name: name5 Designation: Designation5
5 Name: name6 Designation: Designation6
答案 1 :(得分:0)
与您的解决方案非常相似,只使用merged_list = list([x for x in list_1 if x ])
merged_list.extend(x for x in list_2 if x)
和enumerate
代替with
和open
:
close