- """
- 1. 打开文件
- - 路径:
- 相对路径:当前项目(读文件.py)所在的目录下查找需要读取的文件
- 绝对路径:文件--右键--Copy Path/Reference--Absolute Path
- - 模式:
- rb,表示读取文件原始的二进制(r,读 read;b,二进制 binary)
- """
- # 1 打开文件
- # file_object = open('info.txt', mode='rb') # 使用相对路径
- file_object = open('D:/pythonProject/文件操作/info.txt', mode='rb') # 使用绝对路径
- # 2 读取文件内容
- data = file_object.read()
- # 3 关闭文件(在Python文件操作中,使用open()函数打开文件后需要及时关闭文件。如果程序在将文件对象用完后未关闭它,就可能会导致数据丢失、系统资源占用过多,严重时可能会导致系统崩溃。)
- file_object.close()
- print(data) # 读取内容后获得的是二进制内容b'\xe8\xbf\x99\xe6\x98'
- # 4 对内容进行二进制解码操作(使用encode编码成二进制)
- text = data.decode()
- print(text)
- """
- 注意:
- 如果open文件时不传mode,则默认是gbk,会报解码错误
- UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 8: illegal multibyte sequence
- """
- """
- windows环境使用绝对路径
- 1 可以将 \ 修改成 /
- 2 可以将 \ 修改成 \\
- 3 可以在路径前加 r
- """
- # 1 打开文件
- file_object = open(r'D:\pythonProject\文件操作\info.txt', encoding='utf-8') # 不加mode,默认以只读方式打开(mode='r')
- # 2 读取文件内容
- data = file_object.read()
- # 3 关闭文件
- file_object.close()
- print(data)
- import os
- is_exists = os.path.exists('info.txt')
- print(is_exists) # True
-
- not_exists = os.path.exists('info1.txt')
- print(not_exists) # False
文件内容存储一般是Unicode编码,使用的是16位二进制数字表示所有字符
- file_object = open('info.txt', mode='wt+', encoding='utf-8')
- # w模式:先清空文件,再写入内容
- data = file_object.read()
- print(data) # 文件内容清空后输出是空
- # 写入内容
- file_object.write("这是我第一次写入的内容")
-
- # 将光标位置重置为起始位置
- file_object.seek(0)
- """
- 写入内容后默认光标位置是写入内容的最后位置
- 所以读取文件内容从写入内容的最后位置开始读
- 如果不重置光标位置,则读取得内容是空
- """
- data = file_object.read()
- print(data)
模式是r/rt,w/wt,a/at在打开文件时需要加encoding
模式是rb,wb,ab在打开文件时不能加encoding,rb在读完文件后进行decode,wb在写入内容时encode