python 的IO
同步IO
文件IO
读文件
和C++大致一致
f = open('test.txt', 'r')
print(f.read())
f.close()
不过因为比C++的trycatch多了finally,所以之后应该这么做:
try:
f = open('test.txt', 'r')
print(f.read())
finally:
if f:
f.close()
更简单地写法
python 引入了 with
with open('test.txt', 'r') as f:
print(f.read())
更多地参数
- 二进制:
b
字符编码
- 默认是utf8,如果不是utf8的话,就加上
encoding='gbk'
写文件
写文件和读文件类似,只需要把read换成write即可。打开文件的时候 r 换成 w
with open('test.txt', 'w') as f:
f.write('hello world')
StringIO
StringIO是一个内存中的字符串
读写方法和文件类似,只不过没有open()
from io import StringIO
f = StringIO()
f.write('hello world')
print(f.getvalue())
BytesIO
BytesIO是一个内存中的字节流
读写方法和文件类似,只不过没有open()
from io import BytesIO
f = BytesIO()
f.write('hello world'.encode())
print(f.getvalue().decode())
print(f.read())
OS中的文件和目录操作
环境变量
os.environ
是一个字典,里面存放了系统的环境变量os.getenv(key)
获取某个环境变量的值os.putenv(key, value)
设置某个环境变量的值, (普通用户不能用)os.unsetenv(key)
删除某个环境变量(普通用户不能用)
print(os.environ)
print(os.getenv('PATH'))
os.putenv('TEST', 'hello world')
print(os.environ['TEST'])
del os.environ['TEST']
操作目录和文件
os.listdir(path)
列出某个目录下的所有文件名,返回一个列表os.path.abspath(path)
获取绝对路径os.path.join(*paths)
把多个路径合并成一个路径,返回一个字符串os.mkdir(path)
创建一个目录os.rmdir(path)
删除一个空的目录
print(os.listdir('.'))
print(os.path.abspath('.'))
print(os.path.basename(__file__))
print(os.path.dirname(__file__))
print(os.path.join('.', 'test_file.txt'))
print(os.path.exists('./test_file.txt'))
print(os.path.isdir('./test_file.txt'))
print(os.path.split( os.path.abspath(__file__)))
if not os.path.exists('./test_dir'):
os.makedirs('./test_dir')
os.rmdir('./test_dir')
序列化
pickle
pickle是python自带的一个模块,用于序列化和反序列化。
pickle.dump(obj, file)
把对象写入文件中
import pickle
d = dict(name='Bob', age=20, score=88)
with open('test_file.txt', 'wb') as f:
f.write(pickle.dumps(d))
json
s = Student('Bob', 20, 88)
print(student2dict(s))
d = dict(name='Bob', age=20, score=88)
print(json.dumps(d, default=student2dict))
with open('test_file.json', 'w') as f:
json.dump(student2dict(s), f)
with open('test_file.json', 'r') as f:
s = dict2student(json.load(f))
print(s)
print(student2dict(s))