#打开数据文件
infile = open("datacsv", 'r')
names = infilereadline()
names = namesrstrip()split(',')
del names[0] #删除第一行0列空字符
myset = {}
for name in names:
myset[name] = {}
for line in infile:
line = linerstrip()split(',')
movieKey = line[0]
for i in range(len(names)):
myset[names[i]][movieKey] = line[i+1]
从执行效率考虑,用pandas库比较好。
import pandas as pd
df=pdread_csv('d:/datacsv',delimiter='\t')
print(df[df地区=='地区3'])
csv是我接触的比较早的一种文件,比较好的是这种文件既能够以电子表格的形式查看又能够以文本的形式查看。最早接触是在别人的Perl脚本中,或许是为了充分利用Perl的文本处理能力。不过,日常的生活工作中我用到的比较多的倒还是电子表格。
创建一个电子表格如下:
使用Mac中Numbers功能将其导出为csv文件,使用文本查看文件内容如下:
GreydeMac-mini:chapter06 greyzhang$ cat datacsv
index,name,comment,,,,
1,name_01,coment_01,,,,
2,name_02,coment_02,,,,
3,name_03,coment_03,,,,
4,name_04,coment_04,,,,
5,name_05,coment_05,,,,
6,name_06,coment_06,,,,
7,name_07,coment_07,,,,
8,name_08,coment_08,,,,
9,name_09,coment_09,,,,
10,name_10,coment_10,,,,
11,name_11,coment_11,,,,
12,name_12,coment_12,,,,
13,name_13,coment_13,,,,
14,name_14,coment_14,,,,
15,name_15,coment_15,,,,
16,name_16,coment_16,,,,
17,name_17,coment_17,,,,
18,name_18,coment_18,,,,
19,name_19,coment_19,,,,
20,name_20,coment_20,,,,
21,name_21,coment_21,,,,
换用pandas尝试数据文件读取如下:
In [1]: import pandas as pd
In [2]: ls
datacsv datanumbers
In [3]: data = pdread_csv('datacsv')
In [4]: data
Out[4]:
index name comment Unnamed: 3 Unnamed: 4 Unnamed: 5 Unnamed: 6
0 1 name_01 coment_01 NaN NaN NaN NaN
1 2 name_02 coment_02 NaN NaN NaN NaN
2 3 name_03 coment_03 NaN NaN NaN NaN
3 4 name_04 coment_04 NaN NaN NaN NaN
4 5 name_05 coment_05 NaN NaN NaN NaN
5 6 name_06 coment_06 NaN NaN NaN NaN
6 7 name_07 coment_07 NaN NaN NaN NaN
7 8 name_08 coment_08 NaN NaN NaN NaN
8 9 name_09 coment_09 NaN NaN NaN NaN
9 10 name_10 coment_10 NaN NaN NaN NaN
10 11 name_11 coment_11 NaN NaN NaN NaN
11 12 name_12 coment_12 NaN NaN NaN NaN
12 13 name_13 coment_13 NaN NaN NaN NaN
13 14 name_14 coment_14 NaN NaN NaN NaN
14 15 name_15 coment_15 NaN NaN NaN NaN
15 16 name_16 coment_16 NaN NaN NaN NaN
16 17 name_17 coment_17 NaN NaN NaN NaN
17 18 name_18 coment_18 NaN NaN NaN NaN
18 19 name_19 coment_19 NaN NaN NaN NaN
19 20 name_20 coment_20 NaN NaN NaN NaN
20 21 name_21 coment_21 NaN NaN NaN NaN
查看读取出来的结果,看的出结果被处理成了pandas的DataFrame格式。
In [6]: type(data)
Out[6]: pandascoreframeDataFrame
以上就是关于我是一名python新手,想按照如图所示读取csv文件到字典,第一列是电影名,第一行是用户名全部的内容,包括:我是一名python新手,想按照如图所示读取csv文件到字典,第一列是电影名,第一行是用户名、python如何读取csv指定内容所在行的第二列内容、怎么用python读取csv数据等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)