1、文件操作
1.1)编码的相关以及数据类型
字符串类型(str)文字信息,本质上是unicode编码中的二进制
name = “熊辉”
字节类型(bytes)
可表示文字信息,本质上是utf-8/gbk等编码的二进制(对unicode进行压缩,方便文件存储和网络传输。)
name = '熊辉'data = name.encode('utf-8')print(data) #b'\xe7\x86\x8a\xe8\xbe\x89'result = data.decode('utf-8') #decode解编码print(result) #
可表示原始二进制(图片、文件等信息)
1.2)读文件
打开文件的路径,可以是相对路径,也可以是绝对路径
file_object = open('info.txt',mode='rb')data = file_object.read()print(data.decode('utf-8'))
file_object = open('info.txt', mode='rt', encoding='utf-8')data = file_object.read()print(data)file_object.close()
读文件时,文件不存在程序会报错。Traceback (most recent call last):File "/Users/wupeiqi/PycharmProjects/luffyCourse/day09/2.读文件.py", line 2, in <module>file_object = open('infower.txt', mode='rt', encoding='utf-8')FileNotFoundError: [Errno 2] No such file or directory: 'infower.txt'
import osfile_path="E:\python30\day2021-0331\info1.txt"exists = os.path.exists(file_path)if exists:file_object = open('info1.txt',mode='rt',encoding='utf-8')data = file_object.read()file_object.close()print(data)else:print('文件不存在')
1.3)写文件
1.打开文件
# 路径:t1.txt
# 模式:wb(要求写入的内容需要是字节类型)
file_object = open('info1.txt',mode='wb')file_object.write('熊辉'.encode('utf-8'))file_object.close()
写图片等文件f1 = open('a1.png',mode='rb')content = f1.read()f1.close()f2 = open('a2.png',mode='wb')f2.write(content)f2.close()
#案例1:用户注册user = input('请输入用户名:')pwd = input('请输入密码:')data = "{}-{}\n".format(user,pwd)file_object = open('info2.txt',mode='at',encoding='utf-8')file_object.write(data)file_object.close()#案例2:多用户注册file_object = open("info3.txt", mode='at', encoding='utf-8')while True:user = input('请输入用户名:')if user.upper() == "Q":breakpwd = input('请输入密码:')data = "{}-{}\n".format(user,pwd)file_object.write(data)file_object.close()#案例3import requestsres = requests.get(url="https://hbimg.huabanimg.com/c7e1461e4b15735fbe625c4dc85bd19904d96daf6de9fb-tosv1r_fw1200",headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"})with open('a2.png',mode='wb') as file_object:file_object.write(res.content)
