python文件操作相关
1. 读文件
1.1 读文本文件
-
# 1.打开文件 file_object = open('info.txt', mode='rt', encoding='utf-8') # 2.读取文件,赋值给data data = file_object.read() # 3.关闭文件 file_object.close() text = data.decode("utf-8") print(text)
-
注意:1.读取文件时要注意读取文件的路径
2.文件位置写路径时windows的路径中“\”需要转义,或者在路径前加r
file_object = open(r'E:\untitled\info.txt', mode='rt', encoding='utf-8') file_object = open('E:\\untitled\\info.txt', mode='rt', encoding='utf-8')
3.如果文件不存在,程序会报错
import os # 判断文件是否存在 # flag = os.path.exists() 返回布尔值 # exists的参数可以是路径或者文件
-
2. 写文件
-
import os # 判断文件是否存在 # flag = os.path.exists() 返回布尔值 # 1.打开文件 file_object = open('info.txt', mode='wt', encoding='utf-8') # 2.读取文件,赋值给data file_object.write("写文件练习") # 3.关闭文件 file_object.close()
注意:w写入文件时,是先清空文件再写入内容
3.文件打开模式
-
只读:
r
、rt
、rb
(用)-
存在,读
-
不存在,报错
-
-
只写:
w
、wt
、wb
(用)-
存在,清空再写
-
不存在,创建再写
-
-
只写:
x
、xt
、xb
-
存在,报错
-
不存在,创建再写。
-
-
只写:
a
、at
、ab
【尾部追加】(用)-
存在,尾部追加。
-
不存在,创建再写。
-
-
r+、rt+、rb+,默认光标位置:起始位置
-
w+、wt+、wb+,默认光标位置:起始位置(清空文件)
-
x+、xt+、xb+,默认光标位置:起始位置(新文件)
-
a+、at+、ab+,默认光标位置:末尾
4. 常用方法
-
readline() 读一行
-
readlines() 按行读取所有内容
-
flush()将缓冲区的内容刷新到硬盘中
-
seek(num)获取光标的位置,num是数字
5. 上下文管理
-
with open(“*.txt”, mode = “rt”, encoding = “utf-8”) as f: ... #执行完with后的代码后,程序会自动关闭文件
csv格式文件
描述:
逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。
案例
import os
import requests
with open("image.csv", mode="r", encoding="utf-8") as file_object: # 打开准备好的CSV格式的文件
file_object.readline() # 读取第一行标题行
for line in file_object: # 从第二行开始按行读取
userid, name, url = line.strip().split(",") # 去除每行尾的特殊符号,并用逗号分割每行 赋值给每个字段
print(name, url) # 打印字段
res = requests.get(url=url, # 获取下载地址
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.62"
})
if not os.path.exists("image"): # 判断是否存在需要保存到的文件夹
os.makedirs("image") # 不存在文件夹的时候创建文件夹
with open("image/{}.png".format(name), mode="wb") as image_object: # 打开以csv格式中第二个字段命名的文件
image_object.write(res.content) # 将下载的文件写到文件内
ini格式文件
描述:
ini文件是Initialization File的缩写,平时用于存储软件的的配置文件。例如:MySQL数据库的配置文件。
案例
import configparser
config = configparser.ConfigParser()
config.read('files/my.ini', encoding='utf-8')
# config.read('/Users/wupeiqi/PycharmProjects/luffyCourse/day09/files/my.ini', encoding='utf-8')
# 1.获取所有的节点
"""
result = config.sections()
print(result) # ['mysqld', 'mysqld_safe', 'client']
"""
# 2.获取节点下的键值
"""
result = config.items("mysqld_safe")
print(result) # [('log-error', '/var/log/mariadb/mariadb.log'), ('pid-file', '/var/run/mariadb/mariadb.pid')]
for key, value in config.items("mysqld_safe"):
print(key, value)
"""
# 3.获取某个节点下的键对应的值
"""
result = config.get("mysqld","collation-server")
print(result)
"""
# 4.其他
# 4.1 是否存在节点
# v1 = config.has_section("client")
# print(v1)
# 4.2 添加一个节点
# config.add_section("group")
# config.set('group','name','wupeiqi')
# config.set('client','name','wupeiqi')
# config.write(open('files/new.ini', mode='w', encoding='utf-8'))
# 4.3 删除
# config.remove_section('client')
# config.remove_option("mysqld", "datadir")
# config.write(open('files/new.ini', mode='w', encoding='utf-8'))
xml文件
1.读取节点数据
-
from xml.etree import ElementTree as ET content = """ <data> <country name="Liechtenstein" id="999" > <rank>2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Panama"> <rank>69</rank> <year>2026</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data> """ # 获取根标签 root = ET.XML(content) country_object = root.find("country") print(country_object.tag, country_object.attrib) gdppc_object = country_object.find("gdppc") print(gdppc_object.tag,gdppc_object.attrib,gdppc_object.text) # 获取孩子标签 for child in root: # child.tag = conntry # child.attrib = {"name":"Liechtenstein"} print(child.tag, child.attrib) for node in child: print(node.tag, node.attrib, node.text) # 获取孙子标签的text for child in root.iter('year'): print(child.tag, child.text) # 修改节点内容和属性 rank = root.find('country').find('rank') print(rank.text) rank.text = "999" rank.set('update', '2020-11-11') print(rank.text, rank.attrib) ############ 保存文件 ############ tree = ET.ElementTree(root) tree.write("new.xml", encoding='utf-8')
2.构建xml文档实例
-
from xml.etree import ElementTree as ET # 创建根节点 root = ET.Element("famliy") # 创建节点大儿子 son1 = ET.SubElement(root, "son", attrib={'name': '儿1'}) # 创建小儿子 son2 = ET.SubElement(root, "son", attrib={"name": "儿2"}) # 在大儿子中创建一个孙子 grandson1 = ET.SubElement(son1, "age", attrib={'name': '儿11'}) grandson1.text = '孙子' et = ET.ElementTree(root) #生成文档对象 et.write("test.xml", encoding="utf-8")
<famliy> <son name="儿1"> <age name="儿11">孙子</age> </son> <son name="儿2"></son> </famliy>
Excel格式文件
1.sheet
1.1获取sheet
from openpyxl import load_workbook
wb = load_workbook("files/p1.xlsx")
print(wb.sheetnames) # 1.获取excel文件中的所有sheet名称
print((wb.worksheets[0].cell(1, 1)).value) # 选择sheet,基于索引位置,并读取第一行第一列的值
print((wb["数据导出"].cell(1, 1)).value) # 选择sheet,基于索引位置,并读取第一行第一列的值
for sheet in wb:
cell = sheet.cell(1, 1)
print(cell.value)
# 循环输出每个sheet的第一行第一列的值
1.2写sheet
-
创建sheet
from openpyxl import workbook # 引入创建 from openpyxl import load_workbook # 引入读取 wb = workbook.Workbook() sheet = wb.worksheets[0] cell = sheet.cell(1, 1) cell.value = "数据1" # 新建sheet并在第一行第一列填入数据1 sheet.title = "worksheet1" # 修改sheet名称 工作表1------->worksheet1 sheet.sheet_properties.tabColor = "1072BA" # 创建sheet并设置sheet颜色 wb.active = 0 # 默认打开的sheet new_sheet = wb.copy_worksheet(wb["worksheet1"]) new_sheet1 = wb.copy_worksheet(wb["worksheet1"]) new_sheet.title = "worksheet2" new_sheet.title = "worksheet3" del wb["worksheet1"] wb.save("file/p2.xlsx") # 保存sheet
-
操作sheet
from openpyxl import load_workbook from openpyxl.styles import Alignment, Border, Side, Font, PatternFill, GradientFill # 对齐, 边框, 边, 字体, 背景色, 渐变背景色 wb = load_workbook('files/p1.xlsx') sheet = wb.worksheets[1] # horizontal,水平方向对齐方式:"general", "left", "center", "right", "fill", "justify", "centerContinuous", "distributed" # vertical,垂直方向对齐方式:"top", "center", "bottom", "justify", "distributed" # text_rotation,旋转角度。 # wrap_text,是否自动换行。 cell.alignment = Alignment(horizontal='center', vertical='distributed', text_rotation=45, wrap_text=True) diagonal=Side(style="thin", color="483D8B"), # 对角线 diagonalUp=True, # 左下 ~ 右上 diagonalDown=True # 左上 ~ 右下 sheet.row_dimensions[1].height = 50 # 设置行高 sheet.column_dimensions["E"].width = 100 # 设置行宽 sheet.merge_cells("B2:D8") # 合并单元格 B2:D8 sheet.merge_cells(start_row=15, start_column=3, end_row=18, end_column=8) # 合并单元格 B2:D8 sheet.unmerge_cells("B2:D8") # 取消合并单元格 sheet["D2"] = "=B2*C2" # 公式 sheet["D3"] = "=SUM(B3,C3)" # 公式 # idx,要删除的索引位置 # amount,从索引位置开始要删除的个数(默认为1) sheet.delete_rows(idx=1, amount=20) sheet.delete_cols(idx=1, amount=3) sheet.insert_rows(idx=5, amount=10) sheet.insert_cols(idx=3, amount=2) # 插入 # 循环写入从第5行第一列写到第10行第7列 for row in sheet.iter_rows(min_row=5, min_col=1, max_col=7, max_row=10): for cell in row: cell.value = "oo" # 将H2:J10范围的数据,向右移动15个位置、向上移动1个位置 sheet.move_range("H2:J10",rows=1, cols=15) sheet.move_range("B1:D3",cols=10, translate=True) # 带公式时 自动翻译公式translate=True sheet.print_area = "A1:D200" # 打印区域 # 打印时,每个页面的固定表头 sheet.print_title_cols = "A:D" sheet.print_title_rows = "1:3"
1.3压缩文件
-
压缩
import shutil # 1. 压缩文件 """ # base_name,压缩后的压缩包文件 # format,压缩的格式,例如:"zip", "tar", "gztar", "bztar", or "xztar". # root_dir,要压缩的文件夹路径 """ # shutil.make_archive(base_name=r'datafile',format='zip',root_dir=r'files')
-
解压
import shutil # 2. 解压文件 """ # filename,要解压的压缩包文件 # extract_dir,解压的路径 # format,压缩文件格式 """ # shutil.unpack_archive(filename=r'datafile.zip', extract_dir=r'xxxxxx/xo', format='zip')
1.4路径相关
import shutil
import os
# 当前文件的路径
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_dir, 'files', 'info.txt')
import os
-
os方法
函数名 函数说明 getcwd() 返回当前工作目录的绝对路径 listdir(path) 以列表的形式返回当前工作目录下的所有文件和目录 mkdir(目录名) 创建指定的目录 如果指定的目录已存在 则报错 rmdir(目录名) 删除指定的目录 如果指定的目录不存在 则报错 rename(文件名, 新名字) 重命名 remove(文件名) 删除文件 system(命令) 运行命令 shutdow -s -f
-
os.path方法
函数名 函数说明 abspath() 返回指定路径的绝对路径 join() 拼接路径 无论是否存在 split() 拆分路径 无论是否存在 splitext 获取文件的扩展名 无论是否存在 getsize() 获取文件大小 返回字节 isdir() 判断是否为目录 isfile() 判断是否为文件 exists() 判断文件或目录是否存在
-
案例
点击查看代码
# 递归统计文件大小 import os def getSize(path): Sum = 0 ListDir = os.listdir(path) for f in ListDir: newPath = os.path.join(path, f) if os.path.isdir(newPath): Sum += getSize(newPath) if os.path.isfile(newPath): Sum += os.path.getsize(newPath) return Sum path = r'C:\Users\xlg\PycharmProjects\online5' print(getSize(path))
点击查看代码
# 文件检索 import os, time def getFileSuffix(path, fileList, suffix): # 获取目录下的所有文件和目录的列表 ListDir = os.listdir(path) # 循环迭代获取每一个文件或目录 for f in ListDir: # 拼凑新路径 newPath = os.path.join(path, f) # 判断是否为目录 if os.path.isdir(newPath): getFileSuffix(newPath, fileList, suffix) # 判断是否为文件 if os.path.isfile(newPath): # 获取文件后缀 fileSuffix = newPath.split('.')[-1] # 判断是否为要检索得文件 if fileSuffix.upper() == suffix.upper(): # 是则扔进列表中 fileList.append(f) # 将获取到的文件进行展示的函数 def showFile(path, suffix='py'): fileList = [] # 判断路径是否存在 getFileSuffix(path, fileList, suffix) if not fileList: print('您要检索后缀{} 不存在'.format(suffix)) return print('您要检索后缀为:{}的文件个数为:{} 分别是:'.format(suffix, len(fileList))) time.sleep(2) for f in fileList: time.sleep(0.5) print(f) while True: path = input('请输入要检索的路径:') suffix = input('请输入要检索的后缀(默认为py):') if os.path.exists(path): if suffix: showFile(path, suffix) else: showFile(path) else: print('请输入正确的路径')
pickle模块
-
import pickle
dump() 将数据序列化后写入到文件中
dumps() 将数据序列化后直接返回
load() 将数据从文件中饭序列化取出
loads() 将序列化后的数据直接反序列化
点击查看代码
import pickle Dict = {'name': 'lucky'} with open('test_open.py', 'wb') as f: pickle.dump(Dict, f) with open('test_open.py', 'rb') as f: val = pickle.load(f) print(type(val)) print(val)
本文来自博客园,作者:wq512,转载请注明原文链接:https://www.cnblogs.com/wangqi512/p/15100535.html