1、文件操作

1.1)编码的相关以及数据类型

  • 字符串类型(str)文字信息,本质上是unicode编码中的二进制

    name = “熊辉”

  • 字节类型(bytes)

可表示文字信息,本质上是utf-8/gbk等编码的二进制(对unicode进行压缩,方便文件存储和网络传输。)

  1. name = '熊辉'
  2. data = name.encode('utf-8')
  3. print(data) #b'\xe7\x86\x8a\xe8\xbe\x89'
  4. result = data.decode('utf-8') #decode解编码
  5. print(result) #

可表示原始二进制(图片、文件等信息)

1.2)读文件

打开文件的路径,可以是相对路径,也可以是绝对路径

  1. file_object = open('info.txt',mode='rb')
  2. data = file_object.read()
  3. print(data.decode('utf-8'))
  1. file_object = open('info.txt', mode='rt', encoding='utf-8')
  2. data = file_object.read()
  3. print(data)
  4. file_object.close()
  1. 读文件时,文件不存在程序会报错。
  2. Traceback (most recent call last):
  3. File "/Users/wupeiqi/PycharmProjects/luffyCourse/day09/2.读文件.py", line 2, in <module>
  4. file_object = open('infower.txt', mode='rt', encoding='utf-8')
  5. FileNotFoundError: [Errno 2] No such file or directory: 'infower.txt'
  1. import os
  2. file_path="E:\python30\day2021-0331\info1.txt"
  3. exists = os.path.exists(file_path)
  4. if exists:
  5. file_object = open('info1.txt',mode='rt',encoding='utf-8')
  6. data = file_object.read()
  7. file_object.close()
  8. print(data)
  9. else:
  10. print('文件不存在')

1.3)写文件

1.打开文件
# 路径:t1.txt
# 模式:wb(要求写入的内容需要是字节类型)

  1. file_object = open('info1.txt',mode='wb')
  2. file_object.write('熊辉'.encode('utf-8'))
  3. file_object.close()
  1. 写图片等文件
  2. f1 = open('a1.png',mode='rb')
  3. content = f1.read()
  4. f1.close()
  5. f2 = open('a2.png',mode='wb')
  6. f2.write(content)
  7. f2.close()
  1. #案例1:用户注册
  2. user = input('请输入用户名:')
  3. pwd = input('请输入密码:')
  4. data = "{}-{}\n".format(user,pwd)
  5. file_object = open('info2.txt',mode='at',encoding='utf-8')
  6. file_object.write(data)
  7. file_object.close()
  8. #案例2:多用户注册
  9. file_object = open("info3.txt", mode='at', encoding='utf-8')
  10. while True:
  11. user = input('请输入用户名:')
  12. if user.upper() == "Q":
  13. break
  14. pwd = input('请输入密码:')
  15. data = "{}-{}\n".format(user,pwd)
  16. file_object.write(data)
  17. file_object.close()
  18. #案例3
  19. import requests
  20. res = requests.get(
  21. url="https://hbimg.huabanimg.com/c7e1461e4b15735fbe625c4dc85bd19904d96daf6de9fb-tosv1r_fw1200",
  22. headers={
  23. "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"
  24. }
  25. )
  26. with open('a2.png',mode='wb') as file_object:
  27. file_object.write(res.content)