python之文件读写操作笔记

2022-10-17,,,,

对不同类的文件操作,需要调用相关的库文件,一般情况下,可以选择建立:写文件函数和读文件函数。在写文件与读文件函数中

我们可以采用:with  open('文件名','w', encoding='utf8') as f:  上下文管理方式来操作文件。接下来就是简单的代码演练了。

 1 def txt_writer():
 2     """写文件"""
 3     with open('data.txt', 'w', encoding='utf8') as f:
 4         f.write('优品课堂\n')
 5         lines = [
 6             '地址:北京市\n',
 7             'qq:95001678\n',
 8             '网址:http://uke.cc'
 9         ]
10         f.writelines(lines)
11 
12 def txt_read():
13     """读文件"""
14     # open中省略'r',也可以
15     with open('data.txt', encoding='utf8') as f:
16         # 两种方式读取文件
17         # for line in f:
18         #     print(line, end='')
19         reader = f.readlines()  # 这个与f.writelines对应
20         print(reader)
21 
22 if __name__ == '__main__':
23     txt_read()
 1 import json  # 调用json库不可少
 2 
 3 def json_basic():
 4     data = {
 5         "id": 1,
 6         "课程": "python精讲",
 7         "机构": "优品课堂",
 8         "单价": 98.00,
 9         "网址": "http://codr.cn"
10     }
11     print('原始数据')
12     print(data)
13     print('_  ' * 20)
14     json_str = json.dumps(data)
15     print(json_str)
16     print('_  ' * 20)
17     json_data = json.loads(json_str)
18     print(json_data)
19 
20 def json_write_file():
21     """写json文档"""
22     data = {
23         "id": 1,
24         "课程": "python精讲",
25         "机构": "优品课堂",
26         "单价": 98.00,
27         "网址": "http://codr.cn"
28     }
29     with open('data.json', 'w', encoding='utf8') as f:
30         json.dump(data, f)  # 向文件存储数据
31 
32 def json_read_file():
33     """读取json文件"""
34     with open('data.json', 'r', encoding='utf8') as f:
35         data = json.load(f)  # 加载文件中的数据
36         print(data)
37 
38 def json_type_diff():
39     """类型差异"""
40     # print(json.dumps(false))
41     data = {
42         'discontinued': false,  # 在json下false为false
43         'tilte': 'iphone7s',
44         'category': none,  # 在json下none为none
45         'price': 5999.00
46     }
47     print(json.dumps(data))
48 # {"discontinued": false, "tilte": "iphone7s", "category": null, "price": 5999.0}
49 
50 
51 if __name__ == '__main__':
52     # json_basic()
53     # json_write_file()
54     # json_read_file()
55     json_type_diff()
 1 import xlrd
 2 
 3 def xl_read():
 4     """excel读取"""
 5     book = xlrd.open_workbook('product.xlsx')
 6     for sheet in book.sheets():  # 读取excel表里的工作簿在表的下方sheet里
 7         print(sheet.name)        # 这里sheet的别名不能出现空格
 8 
 9 def xl_read_data():
10     """读取数据"""
11     # 用xlrd.open_workbook('文件名.xlxs')方式打开excel文件
12     book = xlrd.open_workbook('product.xlsx')
13     sheet = book.sheet_by_name("product")
14     print('工作簿:{}'.format(sheet.name))
15     print('数据行数:{}'.format(sheet.nrows))
16     print("产品数据")
17     print("=" * 50)
18     for i in range(sheet.nrows):
19         print(sheet.row_values(i))  # 获取索引指定的数据行
20 
21 if __name__ == '__main__':
22     # xl_read()
23     xl_read_data()
 1 import csv  # 调用csv库是不可少的
 2 """先运行csv_write部分即写入csv文件"""
 3 
 4 """这是csv文件的基本操作"""
 5 
 6 def csv_reader():
 7     """读取csv"""
 8 
 9     with open('my_course2.csv', encoding='utf8') as f:
10         reader = csv.reader(f)  # 以列表的方式读取赋值给reader
11         # reader = csv.dictreader(f)  # 以顺序字典表的方式读取赋值给reader
12         headers = next(reader)  # 用next迭代方式打印
13         print(headers)
14         for row in reader:
15             print(row)
16 
17 def csv_write():
18     """写入csv文件"""
19     """"先创建写的内容"""
20     headers = ["编号", "课程", "讲师"]
21     # 不能忘记每一行后面的“,”
22     rows = [
23         (1, "python", "eason"),
24         (2, "c#", "eason"),
25         (3, "django", "eason"),
26         (4, ".net", "eason")
27     ]
28     """newline=''是为了写入文件的每一行不要有空行"""
29     with open('my_course.csv', 'w', encoding='utf8', newline='') as f:
30         writer = csv.writer(f)
31         writer.writerow(headers)  # 写入标头
32         writer.writerows(rows)   # 写入标头以下行writerows比上一行多个s
33 
34 def csv_writer_dict():
35     """以dict形式写入csv"""
36     """"先创建写的内容"""
37     headers = ["id", "title", "org", "url"]
38     # 不能忘记每一行后面的“,”
39     rows = [
40         {'id': 1, 'title': 'python', 'org': 'youpinketang', 'url': 'http://uke.cc'},
41         {'id': 2, 'title': 'python', 'org': 'youpinketang', 'url': 'http://uke.cc'},
42         {'id': 3, 'title': 'python', 'org': 'youpinketang', 'url': 'http://uke.cc'},
43         {'id': 4, 'title': 'python', 'org': 'youpinketang', 'url': 'http://uke.cc'},
44         dict(id=5, title='c#', org='youpinketang', url='http://codr.cn'),
45         dict(id=6, title='c#', org='youpinketang', url='http://codr.cn')
46     ]
47     """通过with... as ...形式方便程序进程管理"""
48     with open('my_course2.csv', 'w', encoding='utf8', newline='') as f:
49         writer = csv.dictwriter(f, headers)  # 以字典表的形式写入文件
50         writer.writeheader()  # 写入第一行标头
51         writer.writerows(rows)  # 写入标头行以下行
52 
53 if __name__ == '__main__':
54     # csv_write()
55     csv_reader()
56     # csv_writer_dict()

 

《python之文件读写操作笔记.doc》

下载本文的Word格式文档,以方便收藏与打印。