python之文件读写操作笔记
2024-09-06 16:09:47
对不同类的文件操作,需要调用相关的库文件,一般情况下,可以选择建立:写文件函数和读文件函数。在写文件与读文件函数中
我们可以采用:with open('文件名','w', encoding='utf8') as f: 上下文管理方式来操作文件。
其中‘w’为打开文件模式,也可以是‘r’,还可以是‘a’
r 以只读方式打开文件。文件的指针将回放在文件的开头,这是默认模式
w 打开一个文件只用于写入。如果该文件已存在则覆盖,如果不存在,就创建新文件
a 打开一个文件用于追加。如果该文件已存在,就从结尾追加。如果没有就新建文件
接下来就是简单的代码演练了。
def txt_writer():
"""写文件"""
with open('data.txt', 'w', encoding='utf8') as f:
f.write('优品课堂\n')
lines = [
'地址:北京市\n',
'QQ:95001678\n',
'网址:http://uke.cc'
]
f.writelines(lines) def txt_read():
"""读文件"""
# open中省略'r',也可以
with open('data.txt', encoding='utf8') as f:
# 两种方式读取文件
# for line in f:
# print(line, end='')
reader = f.readlines() # 这个与f.writelines对应
print(reader) if __name__ == '__main__':
txt_read()
import json # 调用json库不可少 def json_basic():
data = {
"ID": 1,
"课程": "Python精讲",
"机构": "优品课堂",
"单价": 98.00,
"网址": "http://codr.cn"
}
print('原始数据')
print(data)
print('_ ' * 20)
json_str = json.dumps(data)
print(json_str)
print('_ ' * 20)
json_data = json.loads(json_str)
print(json_data) def json_write_file():
"""写json文档"""
data = {
"ID": 1,
"课程": "Python精讲",
"机构": "优品课堂",
"单价": 98.00,
"网址": "http://codr.cn"
}
with open('data.json', 'w', encoding='utf8') as f:
json.dump(data, f) # 向文件存储数据 def json_read_file():
"""读取json文件"""
with open('data.json', 'r', encoding='utf8') as f:
data = json.load(f) # 加载文件中的数据
print(data) def json_type_diff():
"""类型差异"""
# print(json.dumps(False))
data = {
'Discontinued': False, # 在json下False为false
'Tilte': 'iphone7s',
'category': None, # 在json下None为none
'Price': 5999.00
}
print(json.dumps(data))
# {"Discontinued": false, "Tilte": "iphone7s", "category": null, "Price": 5999.0} if __name__ == '__main__':
# json_basic()
# json_write_file()
# json_read_file()
json_type_diff()
import xlrd def xl_read():
"""excel读取"""
book = xlrd.open_workbook('product.xlsx')
for sheet in book.sheets(): # 读取Excel表里的工作簿在表的下方sheet里
print(sheet.name) # 这里sheet的别名不能出现空格 def xl_read_data():
"""读取数据"""
# 用xlrd.open_workbook('文件名.xlxs')方式打开Excel文件
book = xlrd.open_workbook('product.xlsx')
sheet = book.sheet_by_name("product")
print('工作簿:{}'.format(sheet.name))
print('数据行数:{}'.format(sheet.nrows))
print("产品数据")
print("=" * 50)
for i in range(sheet.nrows):
print(sheet.row_values(i)) # 获取索引指定的数据行 if __name__ == '__main__':
# xl_read()
xl_read_data()
import csv # 调用csv库是不可少的
"""先运行csv_write部分即写入csv文件""" """这是csv文件的基本操作""" def csv_reader():
"""读取csv""" with open('my_course2.csv', encoding='utf8') as f:
reader = csv.reader(f) # 以列表的方式读取赋值给reader
# reader = csv.DictReader(f) # 以顺序字典表的方式读取赋值给reader
headers = next(reader) # 用next迭代方式打印
print(headers)
for row in reader:
print(row) def csv_write():
"""写入csv文件"""
""""先创建写的内容"""
headers = ["编号", "课程", "讲师"]
# 不能忘记每一行后面的“,”
rows = [
(1, "Python", "Eason"),
(2, "c#", "Eason"),
(3, "Django", "Eason"),
(4, ".NET", "Eason")
]
"""newline=''是为了写入文件的每一行不要有空行"""
with open('my_course.csv', 'w', encoding='utf8', newline='') as f:
writer = csv.writer(f)
writer.writerow(headers) # 写入标头
writer.writerows(rows) # 写入标头以下行writerows比上一行多个s def csv_writer_dict():
"""以dict形式写入csv"""
""""先创建写的内容"""
headers = ["ID", "Title", "org", "Url"]
# 不能忘记每一行后面的“,”
rows = [
{'ID': 1, 'Title': 'Python', 'org': 'youpinketang', 'Url': 'http://uke.cc'},
{'ID': 2, 'Title': 'Python', 'org': 'youpinketang', 'Url': 'http://uke.cc'},
{'ID': 3, 'Title': 'Python', 'org': 'youpinketang', 'Url': 'http://uke.cc'},
{'ID': 4, 'Title': 'Python', 'org': 'youpinketang', 'Url': 'http://uke.cc'},
dict(ID=5, Title='C#', org='youpinketang', Url='http://codr.cn'),
dict(ID=6, Title='C#', org='youpinketang', Url='http://codr.cn')
]
"""通过with... as ...形式方便程序进程管理"""
with open('my_course2.csv', 'w', encoding='utf8', newline='') as f:
writer = csv.DictWriter(f, headers) # 以字典表的形式写入文件
writer.writeheader() # 写入第一行标头
writer.writerows(rows) # 写入标头行以下行 if __name__ == '__main__':
# csv_write()
csv_reader()
# csv_writer_dict()
最新文章
- 关于C#的继承结论
- Angular Module声明和获取重载
- angular-input
- TP常用函数
- JDBC之PreparedStatement模糊查询
- Oracle 跨库 查询 复制表数据 分布式查询
- [Bayes] Variational Inference for Bayesian GMMs
- .Net及C#基础知识,面试宝典
- 关于IOS开发的基本书籍推荐
- c#+.net常用功能点
- RabbitMQ三种Exchange模式(fanout,direct,topic)的性能比较
- NModbus类库使用
- 51 IP核查询
- Python中的下划线(转)
- cocos jsb工程转html 工程
- mysql query 条件中为空时忽略
- How to Run Syncthing 24/7 as a Windows Service with AlwaysUp
- 计算机顶级会议Rankings &;amp;&;amp; 英文投稿的一点经验
- LocalStorage漏洞分析
- java程序调优系列(一)intern()代替equal()