Python 学习笔记: 文件操作
文件操作
1 打开一个同目录的文本文件,只读方式。
f = open('中文文件1.txt',mode='r',encoding='utf-8') content = f.read() print(content) f.close()
操作方式:只读,只写,追加,读写,写读.....
以什么编码方式储存的文件,就以什么编码打开进行操作。
以rb 方式打开一个文件时, 读取的是byte:
f = open('中文文件1.txt',mode='rb') content = f.read() print(content) f.close()
2 以只写方式写文件, 文件不存在就创建, 存在就覆盖。
f = open('log', mode='w',encoding='utf-8') f.write('了哦发动捐款捐款合计') f.close()
先编码成bytes后再以'rb'方式写入。
f = open('log', mode='wb') f.write('测试中文哦'.encode('utf-8')) f.close()
3 以a模式编写(追加), ab模式
f = open('log',mode='a',encoding='utf-8') f.write('信息中') f.close()
f = open('log',mode='ab') f.write('信息中'.encode('utf-8) f.close()
3 r+ , r+b 的 "读写"模式, 注意光标移动。
先读后, 光标移动到最后, 写入的内容紧跟文件末尾。
f = open('log',mode='r+',encoding='utf-8') print(f.read()) f.write('python信息中') f.close()
先写, 覆盖一部分内容, 读的是后面的内容。
f = open('log',mode='r+',encoding='utf-8') f.write('python') print(f.read()) f.close()
4 a+ 模式, a模式时只能追加写入, a+ 模式时可以读。
f = open('log',mode='a+',encoding='utf-8') f.write('9python') f.seek(0) print(f.read()) f.close()
f.seek(0) 使光标移到文件开始处。
5 read(n) , 读取n个字符, 一个中文字是1个字符。
f = open('log',mode='r+',encoding='utf-8') print(f.read(9)) # read(n) , 读取n 个字符。 英文或者中文, 一个中文字是1个字符。 f.close()
f.seek(n) n 是按照字节移动, 一个中文字是占用三个字节, 移动时如果截断了中文字, 就会出现乱码报错。
f.tell() 显示当前光标的位置。
cout = f.tell()
f.seek(cout-3) # 移动光标到最后一个中文字符前或者三个英文字符前。
6 f.truncate(size) 截去文件中size字节后返回。如果遇到错误截去了半个中文字符, python3会报错。
7 f.readline() 返回一行
8.f.readlines() 返回一个列表, 每个元素是一行(带‘\n’)。
9 with open('filename',mode='r+, encoding='utf-8' as f:
可以不用写关闭文件句柄的语句了。 python负责自动关闭文件。
10. 练习:
username = input('请输入注册用户名:') password = input('请输入注册的密码:') with open('user_info', mode='w',encoding='utf-8') as f: f.write('{}\n{}'.format(username,password)) print('注册成功') print('登录测试。。。') list1=[] with open('user_info', mode='r+', encoding='utf-8') as f1: for line in f1: list1.append(line) print(list1) i=0 while i<3: usr = input('请输入注册用户名:') pwd = input('请输入注册的密码:') if usr == list1[0].strip() and pwd == list1[1].strip(): break print('登录失败') i+=1 print('登录成功')
11 编码的一些知识
#str --->byte encode 编码
s = '二哥'
b = s.encode('utf-8')
print(b)
#byte --->str decode 解码
s1 = b.decode('utf-8')
print(s1)
注意: 如果解码不按照转换时用的编码来解码, 会出现乱码或者错码。 如下:
s = 'abf二哥'
b = s.encode('utf-8')
print(b)
#byte --->str decode 解码
s1 = b.decode('gbk')
print(s1)
输出如下:
b'abf\xe4\xba\x8c\xe5\x93\xa5'
abf浜屽摜