Files
Python_CookBook_repo/5.文件与IO/1.读写文本数据.py
2025-09-10 16:12:45 +08:00

48 lines
1.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

if __name__ == "__main__":
path = "5.文件与IO/1.somefile.txt"
# 如果想要读取文件那open函数是唯一的选择它有很多模式
# # 只读组, 一般用于配置信息
# open(path, 'rb')
# open(path, 'rt')
#
# # 只写覆盖模式,将指针指向文件头,一般用于文件输出或覆盖旧内容
# open(path, 'wb')
# open(path, 'wt')
#
# # 只写追加模式,将指针从默认的文件头指向文件尾
# open(path, 'ab')
# open(path, 'at')
# 如果上面的任何一种模式后面有+,那么将会变成读写模式
# 在打开文件时可以指定文件的编码格式默认编码模式可以使用sys库进行查询
import sys
print(sys.getdefaultencoding())
# 当我们想打开文件的时候不建议直接使用上面的open函数因为这样需要每次记住手动关闭打开的文件像这样
# 当然二进制写入不需要指定encoding 正常来说需要指定encoding='utf-8'
a = open(path, 'wb')
a.write(b'Hello Python File\n')
a.close()
# 我们可以使用with语句来为文件创建一个上下文环境在程序离开with的程序段以后会自动关闭文件
with open(path, 'rb') as f:
# 记住如果是二进制写入解出来的时候要用utf-8解码一下
print(f.read())
# 可以看到文件已经被关闭了
print(f.closed)
# 在UNIX和Windows上换行符不太相同UNIX是\n而windows是\r\n
# Python在读取文件时做了内置的转换统一换行符为\n,如果不需要这种转换可以设置newline=''
open(path, 'rb', newline='')
# 如果遇见解码错误只需要更换encoding就行, 也可以设置错误解决方案字段errors
open(path, 'rb', encoding='utf-8', errors='replace')