【Python】文件读写
写操作
./1/write.py
content = "Python is the most popular language"
with open("test.txt", "w") as f:
f.write(content)
~$ cd ./1
~/1$ python write.py
读操作
./1/read.py
with open("test.txt") as f:
print(f.read())
~$ cd ./1
~/1$ python read.py
Python is the most popular language
中文的读写
./1/writeChinese.py
content = "Python是当下最流行的语言"
with open("chinese.txt", "w", encoding='utf-8') as f:
f.write(content)
./1/readChinese.py
with open("chinese.txt", encoding='utf-8') as f:
print(f.read())
~$ cd ./1
~/1$ python writeChinese.py
~/1$ python readChinese.py
Python是当下最流行的语言
./1/chinese.txt
Python是当下最流行的语言
读写模式
模式 | 含义 |
---|---|
r(default) | 只读 |
w | 只写。若文件已存在,则覆盖原文件的内容 |
x | 以只读方式创建新文件。若文件已存在,则抛出FileExistsError 错误 |
a | 以追加方式打开文件。若文件已存在,在其尾部追加数据。若文件不存在,创建新文件 |
rb | 二进制只读 |
wb | 二进制只写。若文件已存在,则覆盖原文件的内容 |
xb | 以二进制只读方式创建新文件。若文件已存在,则抛出FileExistsError 错误 |
ab | 以二进制追加方式打开文件。若文件已存在,在其尾部追加数据。若文件不存在,创建新文件 |
r+/rb+/w+/wb+/x+/xb+/a+/ab+ | 以读写方式打开,其他的含义见上。如a是以写追加方式打开,而a+是以读写追加方式打开 |
json文件的读写操作
./1/writeJson.py
import json
data = {
"name": "Bertramoon",
"sex": "male"
}
# json.dumps()方法将Python的dict类转化为json字符串
with open("testJson.json", "w") as f:
f.write(json.dumps(data))
./1/readJson.py
import json
with open("testJson.json") as f:
data = json.loads(f.read())
print(type(data))
[print(f"{key}: {value}") for key, value in data.items()]
~$ cd ./1
~/1$ python writeJson.py
~/1$ python readJson.py
<class 'dict'>
name: Bertramoon
sex: male
./1/testJson.json
{"name": "Bertramoon", "sex": "male"}
你可能觉得写入的排版不是很喜欢,而且json对象有时候有中文。那么,接下来我们再演示一个样例吧
./1/writeJsonChinese.py
import json
data = {
"university": "北京大学",
"city": "北京市"
}
# json.dumps()方法将Python的dict类转化为json字符串
with open("testJsonChinese.json", "w", encoding='utf-8') as f:
# indent代表缩进的字符数,控制排版。ensure_ascii表示是否编码形式存储,如果False的话,则会以我们所见的中文形式(字符集)存储
f.write(json.dumps(data, indent=4, ensure_ascii=False))
./1/readJsonChinese.py
import json
with open("testJsonChinese.json", encoding='utf-8') as f:
data = json.loads(f.read())
print(type(data))
[print(f"{key}: {value}") for key, value in data.items()]
~$ cd ./1
~/1$ python writeJsonChinses.py
~/1$ python readJsonChinese.py
<class 'dict'>
university: 北京大学
city: 北京市
./1/testJsonChinese.json
{
"university": "北京大学",
"city": "北京市"
}
yaml文件的读写操作
./1/writeYaml.py
import yaml
from datetime import date
class Student(object):
def __init__(self, no, name, age):
self.no = no
self.name = name
self.age = age
data = {
'student': [
Student('1', '张三', '22'),
Student('2', '李四', '21')
],
'university': '北京大学',
'city': '北京市',
'today': date.today()
}
with open("testYaml2.yml", "w", encoding='utf-8') as f:
f.write(yaml.dump(data, allow_unicode=True))
./1/readYaml.py
import yaml
class Student(object):
def __init__(self, no, name, age):
self.no = no
self.name = name
self.age = age
def __str__(self):
return f"{self.no} - {self.name} - {self.age}"
with open("testYaml2.yml", encoding='utf-8') as f:
config = yaml.unsafe_load(f)
print(type(config))
[print(f"{key} {type(value)}: {value}") for key, value in config.items()]
[print(item) for item in config['student']]
~$ cd ./1
~/1$ python writeYaml.py
~/1$ python readYaml.py
<class 'dict'>
city <class 'str'>: 北京市
student <class 'list'>: [<__main__.Student object at 0x000001712EFE4370>, <__main__.Student object at 0x000001712EFE43D0>]
today <class 'datetime.date'>: 2021-05-09
university <class 'str'>: 北京大学
1 - 张三 - 22
2 - 李四 - 21
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/97114.html