CSV写入与读取Python
1#写入CSV2import csv
3 csvfile=open("d://text1.csv","w",newline="") #newline为空可以防止写入时空开一行空白行
4 writer=csv.writer(csvfile)
5 writer.writerow(["姓名","年龄","编号"]) #writerow写入一行数据
6 data=[("夏明","18","125846"),("小新","22","159345")] #写入元组与列表一样
7 writer.writerows(data) #writerows写入多行数据
8 csvfile.close()
#读取CSVimport csv
csvfile=open("d://text1.csv","r")
#reader1=csv.reader(csvfile) #以列表形式输出
reader2=csv.DictReader(csvfile) #以字典形式输出,第一行作为键
#rows1=[row for row in reader1]
rows2=[row for row in reader2]
#print("列表:",rows1)
print("字典:",rows2)
#运行结果
#列表: [["姓名", "年龄", "编号"], ["夏明", "18", "125846"], ["小新", "22", "159345"]]
#字典: [OrderedDict([("姓名", "夏明"), ("年龄", "18"), ("编号", "125846")]), OrderedDict([("姓名", "小新"), ("年龄", "22"), ("编号", "159345")])]
#读取某行数据import csv
csvfile=open("d://text1.csv","r")
"""reader=csv.reader(csvfile)
for row in reader:
if "夏明" in row:
print(row)"""
reader=csv.DictReader(csvfile)
for row in reader:
if row["姓名"]=="小新":
print(row)
#运行结果:
# ["夏明", "18", "125846"]
# OrderedDict([("姓名", "小新"), ("年龄", "22"), ("编号", "159345")])
以上是 CSV写入与读取Python 的全部内容, 来源链接: utcz.com/z/530039.html