1) 文件操作

  • 字符编码

字符串类型(str)在程序中用于表示文字信息,本质上是unicode编码的二进制
字节类型(bytes),本质上utf-8/gbk编码,表示原始二进制(图片,文件等信息)

  1. name = "熊纹理"
  2. data = name.encode('utf-8') ---字节
  3. print(data)
  4. result = data.decode('utf-8') --字符串
  5. print(result)

1.1)读文件

  • 读文本文件

注意事项:

  • 关于路径,可以相对路径,也可以绝对路径
  • windows系统中写绝对路径冗余出问题,用r”c:\new\info.txt”
  • 读文件时,文件不存在程序会报错
    1. import os
    2. exists = os.path.exists("info.txt")
    3. print(exists) #存在就返回true
    4. if exists:
    5. file_object = open('info.txt',mode='rt',encoding='utf-8')
    6. data = file_object.read()
    7. file_object.close()
    8. print(data)
    9. else:
    10. print('文件不存在')
    ```bash

    打开文件

    file_object = open(‘info.txt’,mode=’rb’)

    读取文件

    data = file_object.read()

    关闭文件

    file_object.close() print(data)

    结果

    b’hello world\r\n\xe6\x88\x91\xe6\x9d\xa5\xe8\x87\xaa\xe6\xb1\x9f\xe8\xa5\xbf\r\nziioffice’

print(data.decode()) (由字节类型转为字符串类型)

打开文件(以文本打开)

file_object = open(‘info.txt’,mode=’rt’,encoding=’utf-8’)

读取文件

data = file_object.read()

关闭文件

file_object.close() print(data)

结果

hello world 我来自江西 ziioffice

  1. ```bash
  2. 读一张图片
  3. #打开文件
  4. file_object = open('a1.jpg',mode='rb')
  5. #读取文件
  6. data = file_object.read()
  7. #关闭文件
  8. file_object.close()
  9. print(data)

模式详解

  1. #只读 r,rb,rt
  2. 存在,读
  3. 不存在,报错
  4. #只写 w,wb,wt
  5. 存在,清空在写
  6. 不存在,创建在写
  7. #只写 x,xb,xt (几乎不用)
  8. 存在: 报错
  9. 不存在: 创建在写
  10. #只写 a,ab,at (尾部追加)
  11. 存在: 尾部追加
  12. 不存在: 创建在写
  13. #读写
  14. r+ rb+ 默认光标起始位置
  15. w+ wb+ 默认光标起始位置,清空文件
  16. a+ ab+ 默认光标起始位置,不清空文件(追加)
  17. r:
  18. w: 写(会先清空文件,在写)
  19. a 写(追加写)
  20. b: 二进制
  21. t: 文本
  1. file_object = open('info1.txt',mode='rt+')
  2. data = file_object.read()
  3. print(data)
  4. file_object.write("aaa")
  5. print(data)
  6. file_object.close()
  1. #读所有
  2. read() #常用操作
  3. #读n个字符
  4. read(2)
  5. #读一行
  6. readline()
  7. #读所有行
  8. readlines() #写到列表
  9. #循环读 (常用操作)
  10. file = open("info1.txt",mode="r")
  11. for line in file:
  12. print(line.strip())
  13. file.close()

1.2) 写文件

  • 写文本文件

    1. #打开文件
    2. file_object = open('info1.txt',mode='wb')
    3. #写文件
    4. file_object.write('兄云'.encode('utf-8'))
    5. #关闭
    6. file_object.close()
    1. #打开文件
    2. file_object = open('info1.txt',mode='wt',encoding='utf-8') #默认为utf-8
    3. #写文件
    4. file_object.write('兄云')
    5. #关闭
    6. file_object.close()
  • 写图片等文件 ```bash f1=open(“a1.png”,mode=”rb”) content=f1.read() f1.close()

file_object=open(“a2.png”,mode=”wb”) file_object.write(content) file_object.close()

  1. ```bash
  2. user = input("请输入用户名:")
  3. pwd = input("请输入密码:")
  4. data = "{}-{}".format(user,pwd)
  5. file_object = open("info1.txt",mode="wt")
  6. file_object.write(data)
  7. file_object.close()
  8. #多用户注册
  9. file_object = open("info1.txt",mode="wt")
  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()
  1. #如何利用python向某个网站发送请求获取数据
  2. #下载第三方模块
  3. (venv) E:\python>pip install requests
  4. #使用第三方模块
  5. import requests
  6. res = requests.geturl="网址"
  7. 案例1
  8. import requests
  9. res = requests.get(
  10. url="https://www.php.net/manual/zh/class.commonmark-node-document.php",
  11. headers={
  12. "User-Agent": "User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
  13. }
  14. )
  15. file_object = open("info2.txt",mode="wb")
  16. file_object.write(res.content)
  17. file_object.close()
  18. 案例2 下载一张图片
  19. import requests
  20. res = requests.get(
  21. url="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1887089220,2670743537&fm=26&gp=0.jpg",
  22. headers={
  23. "User-Agent": "User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
  24. }
  25. )
  26. file_object = open("a1.jpg",mode="wb")
  27. file_object.write(res.content)
  28. file_object.close()

注意事项:

  • 关于路径,支持绝对路径和相对路径
  • 当文件不存在,w模式会新建在写入内容
  • 当文件存在,w模式会清空文件

1.3)游标

  1. #flush 刷新硬盘
  2. #移动光标 seek() 字节,(一个汉字3个字节)
  3. r模式: 光标移动到指定字节的位置
  4. a模式: 移动光标没用,会永远写到文件尾部
  5. #获取当前光标的位置 tell()
  6. f = open('info1.txt',mode='r+',encoding="utf-8")
  7. p1 = f.tell()
  8. print(p1) # 0
  9. f.read(3) # 这里3表示3个字符
  10. p2 = f.tell()
  11. print(p2) # 9
  12. f.close()

1.4)with上下文管理 (非常重要)
之前对文件进行操作,每次都要打开和关闭文件,比较繁琐且容易关闭文件

  1. with open('info1.txt',mode='rb') as f:
  2. data = f.read()
  3. print(data)
  4. #结果
  5. b'aaa'
  6. with open支持同时打开多个文件
  1. user_dict = {}
  2. with open('files/access.log',mode='r',encoding='utf-8') as file:
  3. for line in file:
  4. user_ip = line.split(" ")[0]
  5. if user_ip in user_dict:
  6. user_dict[user_ip] += 1
  7. else:
  8. user_dict[user_ip] = 1
  9. print(user_dict)
  1. with open('info.conf', mode='r', encoding='utf-8') as f1, open('info1.conf', mode='w', encoding='utf-8') as f2:
  2. for line in f1:
  3. new_line = line.replace('aaa', 'a1')
  4. f2.write(new_line)
  5. import shutil
  6. shutil.move('info1.conf', 'info.conf') # 重命名文件

2)csv格式文件
用固定的分隔符,分割数据,一般用逗号

  1. import requests
  2. import os
  3. with open('file/mv.csv',mode='r',encoding='utf-8') as file_object:
  4. file_object.readline()
  5. for line in file_object:
  6. user_id,username,url_address = line.strip().split(',')
  7. print(username,url)
  8. #根据url下载图片
  9. res = request.get(
  10. url = url_address,
  11. headers={
  12. "User-Agent": "User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
  13. }
  14. )
  15. #将图片写入到文件 确保images文件夹存在
  16. if not os.path.exists("images"):
  17. #创建images目录
  18. os.makedirs("images")
  19. with open("images/{}.jpg".format(username),mode="wb") as img_object:
  20. img_object.write(res.content)

3)ini格式文件
ini文件平常用于存储软件的配置文件,如下

  1. [client]
  2. port=3306
  3. socket=/data/mysql.sock
  4. default-character-set=utf8mb4
  5. [mysql]
  6. default-character-set=utf8mb4
  7. [mysqld]
  8. character-set-client-handshake=FALSE
  9. character-set-server=utf8mb4
  10. collation-server=utf8mb4_general_ci
  11. init_connect='SET NAMES utf8mb4'
  12. port=3306
  13. socket=/data/mysql.sock
  14. key_buffer_size=16M
  15. max_allowed_packet=1M
  16. table_open_cache=64
  17. sort_buffer_size=512K
  • 读取所有节点

    1. #读取所有节点
    2. import configparser
    3. config=configparser.ConfigParser()
    4. config.read('my.cnf',encoding='utf-8')
    5. res=config.sections()
    6. print(res)
  • 读取节点下的值 ```python import configparser config=configparser.ConfigParser() config.read(‘my.cnf’,encoding=’utf-8’) res=config.sections() for node in res: data = config.items(node) print(data) #以元组的形式记录每一条键值

    [(‘character-set-client-handshake’, ‘FALSE’), (‘character-set-server’, ‘utf8mb4’), (‘collation-server’, ‘utf8mb4_general_ci’), (‘init_connect’, “‘SET NAMES utf8mb4’”), (‘port’, ‘3306’), (‘socket’, ‘/data/mysql.sock’), (‘key_buffer_size’, ‘16M’), (‘max_allowed_packet’, ‘1M’), (‘table_open_cache’, ‘64’), (‘sort_buffer_size’, ‘512K’)]

  1. - 获取节点下的键值
  2. ```python
  3. import configparser
  4. config=configparser.ConfigParser()
  5. config.read('my.cnf',encoding='utf-8')
  6. res=config.sections()
  7. for node in res:
  8. data = config.items(node)
  9. for key,value in data:
  10. print(key,value)
  • 获取节点下键对应的值

    1. import configparser
    2. config=configparser.ConfigParser()
    3. config.read('my.cnf',encoding='utf-8')
    4. result = config.get('mysqld','init_connect')
    5. print(result)
  • 追加节点等其他操作 ```python

    判断节点是否存在

    config.has_section(‘client’)

    追加节点

    import configparser config=configparser.ConfigParser() config.read(‘my.cnf’,encoding=’utf-8’) config.add_section(‘groups’) config.write(open(‘my.cnf’,mode=’w’,encoding=’utf-8’))

追加节点数据

import configparser config=configparser.ConfigParser() config.read(‘my.cnf’,encoding=’utf-8’) if not config.has_section(‘groups’): config.add_section(‘groups’) config.set(‘groups’,’ip’,’172.19.156.142’) config.write(open(‘my.cnf’,mode=’w’))

删除节点数据

import configparser config=configparser.ConfigParser() config.read(‘my.cnf’,encoding=’utf-8’) config.remove_option(‘groups’,’name’) config.write(open(‘my.cnf’,mode=’w’))

  1. 4xml格式文件
  2. ```python
  3. from xml.etree import ElementTree as ET
  4. #读取文件
  5. tree = ET.parse('context.xml')
  6. #打开根标签
  7. root = tree.getroot()
  8. print(root)
  9. #读取节点数据
  10. for child in root:
  11. #print(child.tag,child.attrib)
  12. for node in child:
  13. print(node.tag,node.attrib,node.text)
  14. #获取某一个标签
  15. contry_object = root.find('contry')
  16. print(contry_object.tag,contry_object.attribe)
  17. rank_object=contry_object.find('rank')
  18. print(rank_object.tag,rank_object.atrribe,rank_object.text)
  19. #修改和删除节点
  20. root = ET.XML(content)
  21. rank = root.find('contry').find('rank')
  22. rank.text = 999 #修改
  23. rank.set('update','2020-11-11') #添加属性
  24. tree = ET.ElementTree(root)
  25. tree.write('new.xml',encoding='utf-8')
  26. #删除
  27. root.remove(root.find('contry').find('address'))
  28. tree = ET.ElementTree(root)
  29. tree.write('new.xml',encoding='utf-8')

5)excel文件

  • 读取sheet ```python

    安装第三方模块

    (venv) E:\python>pip install openpyxl

读sheet

from openpyxl import load_workbook wb = load_workbook(‘files/py.xlsx’) 1)读取excel文件中的所有sheet名称 print(wb.sheetnames) 2)选择sheet,基于sheet名称 sheet = wb[“第一季度”] cell = sheet.cell(1,2) #第一行第二列 print(cell.value) #打印该单元格值

3)选择sheet,基于索引 sheet = wb.worksheets[0] cell = sheet.cell(1,2) print(cell.value)

循环所有sheet,读取每一个sheet的第一行第二列

for name in wb.sheetnames: sheet1 = wb[name] cell = sheet1.cell(1,2) print(cell)

  1. - 读单元格
  2. ```python
  3. from openpyxl import load_workbook
  4. wb = load_workbook('files/py.xlsx')
  5. sheet = wb.worksheets[0]
  6. cell = sheet.cell(1,1) #单元格第一行第一列
  7. print(cell.value) #单元格的文本内容
  8. #单元格的样式
  9. print(cell.font) #字体
  10. print(cell.style) #样式
  11. print(cell.alignment) #排列清空
  12. #获取具体位置的单元格
  13. c1 = sheet['a2']
  14. print(c1.value)
  15. #获取N行所有的单元格
  16. sheet[1] #获取第一行所有单元格 第一个元组
  17. for cell in sheet[1]:
  18. print(cell.value) #展示第一行的单元格内容
  19. #获取所有行的单元格,获取某列数据
  20. for row in sheet.rows:
  21. print(row[0].value,row[1].value)
  22. #获取所有列的数据
  23. for col in sheet.columns:
  24. print(col[0].value) #取每一列的第一行数据

6)压缩文件

7)案例

  1. data_list = [11,22,34,45]
  2. for i,item in enumerate(data_list,2):
  3. print(i,item)
  4. #结果
  5. 2 11
  6. 3 22
  7. 4 34
  8. 5 45
  • 用户注册及登录 ```python

    文件路径处理

    import os basedir = os.path.dirname(os.path.abspath(_file)) ob_file_path = os.path.join(base_dir,’registry.csv’)

用户注册

while True: choice = input(“是否进行用户注册(Y/N):”) choice = choice.upper() if choice not in {“Y”,”N”}: print(“输入格式错误,请重新输入:”) continue if choice == “N” or choice == “n”: break with open(ob_file_path,mode=’a’,encoding=’utf-8’) as file_object: while True: user = input(“请输入用户名(Q/q退出):”) if user.upper() == “Q”: break pwd = input(“请输入密码:”) file_object.write(“{},{}\n”.format(user,pwd)) file_object.flush()

用户登录

print(“欢迎使用**系统,请登录:”) username = input(“请输入用户名(Q/q退出): “) password = input(“请输入密码:”)

if not os.path.exists(ob_file_path): print(“用户文件不存在”) else: with open(ob_file_path,mode=’r’,encoding=’utf-8’) as file_object: for line in file_object: user,pwd = line.strip().split(“,”) if username == user and password == pwd: print(“登录成功”) else: print(“用户名或密码错误”)

  1. 2、获取天气存到excel
  2. ```python
  3. #文件路径处理
  4. import os
  5. import requests
  6. from xml.etree import ElementTree as ET
  7. from openpyxl import workbook
  8. #处理文件路径
  9. base_dir = os.path.dirname(os.path.abspath(__file__))
  10. ob_file_path = os.path.join(base_dir,'weather.xlsx')
  11. #创建excel且默认会创建一个sheet
  12. wb = workbook.Workbook()
  13. del wb["Sheet"]
  14. while True:
  15. city = input("请输入城市(Q/q退出): ")
  16. if city.upper() == "Q":
  17. break
  18. url = "http://ws.webxml.com.cn//WebServices/WeatherWebService.aspx/getWeatherbyCityName?theCityName={}".format(city)
  19. res = requests.get(url=url)
  20. #print(res.text)
  21. #提取xml的值
  22. root = ET.xml(res.text)
  23. #创建sheet
  24. sheet = wb.create_sheet(city)
  25. for row_index,node in enumerate(root,1):
  26. text = node.text
  27. cell = sheet.cell(row_index,1)
  28. cell.value = text
  29. wb.write(ob_file_path)
  • 解析ini文件,存到excel表格 ```python import os import configparser from openpyxl import workbook from openpyxl.styles import Alignment,Border,Side,Font,PatternFill

    文件路径处理

    basedir = os.path.dirname(os.path.abspath(_file)) file_path = os.path.join(base_dir,”my.ini”) target_excel_file_path = os.path.join(base_dir,”my.xlsx”)

    创建excel

    wb = workbook.Workbook() del wb[“Sheet”]

解析ini文件

config = configparser.ConfigParser() config.read(file_path,encoding=’utf-8’)

循环获取每个节点

for section in config.sections(): sheet = wb.create_sheet(section) side = Side(style=”thin”,color=”000000”) border = Border(top=side,bottom=side,left=side,right=side) align = Alignment(horizontal=”center”,vertical=”center”) title_dict = {“A1”: “键”, “B1”:”值”} for postition,text in title_dict.items(): cell = sheet[postition] cell.value = text cell.alignment = align cell.fill = PatternFill(“solid”,fgColor=”64951d”) cell.font = Font(name=”微软雅黑”, color=”FFFFFF”) cell.border = border row_index = 2 for group in config.items(section): for col,text in enumerate(group,1): cell = sheet.cell(row_index,col) cell.alignment = align cell.border = border cell.value = text row_index += 1 wb.save(target_excel_file_path) ```