如何快速找回意外删除的Excel文件?
1166
2022-05-30
csv文件 读取保存操作
官方文档:https://docs.Python.org/3/library/csv.html
写入
# -*- encoding: utf-8 -*- import csv from io import StringIO from urllib import urlopen # 按行元组参数写入 def writerCsv1(): f = open("data.csv", "w") writer = csv.writer(f) for i in range(100): writer.writerow((i+1, i+2, i+3)) f.close() # 按行字典参数写入 def writerCsv2(): f = open("data.csv", "w") writer = csv.DictWriter(f, ["name", "age"]) for i in range(100): dct = {"name":i+1, "age": i+2} writer.writerow(dct) f.close() print("写入成功!") writerCsv2()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
读取
要读取的文件
# MontyPythonAlbums.csv Name,Year Monty Python's Flying Circus,1970 Another Monty Python Record,1971 Monty Python's Previous Record,1972
1
2
3
4
5
6
# 按行读取列表 def readerCsv1(): # 读取网络文件 # url = "http://www.pythonscraping.com/files/MontyPythonAlbums.csv" # data = urlopen(url).read() # 读取本地文件 data = open("MontyPythonAlbums.csv", "r").read().decode('utf-8') print type(data) data_file = StringIO(data) # 字符串转为io对象 csv_reader = csv.reader(data_file) for row in csv_reader: print(row) """ ['Name', 'Year'] ["Monty Python's Flying Circus", '1970'] """ # readerCsv1() # 按行读取列表 def readerCsv2(): f = open("MontyPythonAlbums.csv", "r") csv_reader = csv.reader(f) for row in csv_reader: print(row) """ ['Name', 'Year'] ["Monty Python's Flying Circus", '1970'] """ f.close() # readerCsv2() # 按行读取字典,第一行为key def readerCsv3(): f = open("MontyPythonAlbums.csv", "r") csv_reader = csv.DictReader(f) for row in csv_reader: print(row) # {'Name': "Monty Python's Flying Circus", 'Year': '1970'} f.close() # readerCsv3()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Python
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。