python格式文件

CSV格式文件

逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)

ID,用户名,头像
26044585,Hush,https://hbimg.huabanimg.com/51d46dc32abe7ac7f83b94c67bb88cacc46869954f478-aP4Q3V
19318369,柒十一,https://hbimg.huabanimg.com/703fdb063bdc37b11033ef794f9b3a7adfa01fd21a6d1-wTFbnO
15529690,Law344,https://hbimg.huabanimg.com/b438d8c61ed2abf50ca94e00f257ca7a223e3b364b471-xrzoQd
18311394,Jennah·,https://hbimg.huabanimg.com/4edba1ed6a71797f52355aa1de5af961b85bf824cb71-px1nZz
18009711,可洛爱画画,https://hbimg.huabanimg.com/03331ef39b5c7687f5cc47dbcbafd974403c962ae88ce-Co8AUI
30574436,花姑凉~,https://hbimg.huabanimg.com/2f5b657edb9497ff8c41132e18000edb082d158c2404-8rYHbw
17740339,小巫師,https://hbimg.huabanimg.com/dbc6fd49f1915545cc42c1a1492a418dbaebd2c21bb9-9aDqgl
18741964,桐末tonmo,https://hbimg.huabanimg.com/b60cee303f62aaa592292f45a1ed8d5be9873b2ed5c-gAJehO
30535005,TANGZHIQI,https://hbimg.huabanimg.com/bbd08ee168d54665bf9b07899a5c4a4d6bc1eb8af77a4-8Gz3K1
31078743,你的老杨,https://hbimg.huabanimg.com/c46fbc3c9a01db37b8e786cbd7174bbd475e4cda220f4-F1u7MX
25519376,尺尺寸,https://hbimg.huabanimg.com/ee29ee198efb98f970e3dc2b24c40d89bfb6f911126b6-KGvKes
21113978,C-CLong,https://hbimg.huabanimg.com/7fa6b2a0d570e67246b34840a87d57c16a875dba9100-SXsSeY
24674102,szaa,https://hbimg.huabanimg.com/0716687b0df93e8c3a8e0925b6d2e4135449cd27597c4-gWdv24
30508507,爱起床的小灰灰,https://hbimg.huabanimg.com/4eafdbfa21b2f300a7becd8863f948e5e92ef789b5a5-1ozTKq
12593664,yokozen,https://hbimg.huabanimg.com/cd07bbaf052b752ed5c287602404ea719d7dd8161321b-cJtHss
16899164,一阵疯,https://hbimg.huabanimg.com/0940b557b28892658c3bcaf52f5ba8dc8402100e130b2-G966Uz
847937,卩丬My㊊伴er彎,https://hbimg.huabanimg.com/e2d6bb5bc8498c6f607492a8f96164aa2366b104e7a-kWaH68
31010628,慢慢即漫漫,https://hbimg.huabanimg.com/c4fb6718907a22f202e8dd14d52f0c369685e59cfea7-82FdsK
13438168,海贼玩跑跑,https://hbimg.huabanimg.com/1edae3ce6fe0f6e95b67b4f8b57c4cebf19c501b397e-BXwiW6
28593155,源稚生,https://hbimg.huabanimg.com/626cfd89ca4c10e6f875f3dfe1005331e4c0fd7fd429-9SeJeQ
28201821,合伙哼哼,https://hbimg.huabanimg.com/f59d4780531aa1892b80e0ec94d4ec78dcba08ff18c416-769X6a
28255146,漫步AAA,https://hbimg.huabanimg.com/3c034c520594e38353a039d7e7a5fd5e74fb53eb1086-KnpLaL
30537613,配䦹,https://hbimg.huabanimg.com/efd81d22c1b1a2de77a0e0d8e853282b83b6bbc590fd-y3d4GJ
22665880,日后必火,https://hbimg.huabanimg.com/69f0f959979a4fada9e9e55f565989544be88164d2b-INWbaF
16748980,keer521521,https://hbimg.huabanimg.com/654953460733026a7ef6e101404055627ad51784a95c-B6OFs4
30536510,“西辞”,https://hbimg.huabanimg.com/61cfffca6b2507bf51a507e8319d68a8b8c3a96968f-6IvMSk
30986577,艺成背锅王,https://hbimg.huabanimg.com/c381ecc43d6c69758a86a30ebf72976906ae6c53291f9-9zroHF
26409800,CsysADk7,https://hbimg.huabanimg.com/bf1d22092c2070d68ade012c588f2e410caaab1f58051-ahlgLm
30469116,18啊全阿,https://hbimg.huabanimg.com/654953460733026a7ef6e101404055627ad51784a95c-B6OFs4
15514336,W/小哥,https://hbimg.huabanimg.com/a30f5967fc0acf81421dd49650397de63c105b9ead1c-nVRrNl
17473505,椿の花,https://hbimg.huabanimg.com/0e38d810e5a24f91ebb251fd3aaaed8bb37655b14844c-pgNJBP
19165177,っ思忆゜♪,https://hbimg.huabanimg.com/4815ea0e4905d0f3bb82a654b481811dadbfe5ce2673-vMVr0B
16059616,格林熊丶,https://hbimg.huabanimg.com/8760a2b08d87e6ed4b7a9715b1a668176dbf84fec5b-jx14tZ
30734152,sCWVkJDG,https://hbimg.huabanimg.com/f31a5305d1b8717bbfb897723f267d316e58e7b7dc40-GD3e22
24019677,虚无本心,https://hbimg.huabanimg.com/6fdfa9834abe362e978b517275b06e7f0d5926aa650-N1xCXE
16670283,Y-雨后天空,https://hbimg.huabanimg.com/a3bbb0045b536fc27a6d2effa64a0d43f9f5193c177f-I2vHaI
21512483,汤姆2,https://hbimg.huabanimg.com/98cc50a61a7cc9b49a8af754ffb26bd15764a82f1133-AkiU7D
16441049,笑潇啸逍小鱼,https://hbimg.huabanimg.com/ae8a70cd85aff3a8587ff6578d5cf7620f3691df13e46-lmrIi9
24795603,⁢⁢⁢⁢⁢v,https://hbimg.huabanimg.com/a7183cc3a933aa129d7b3230bf1378fd8f5857846cc5-3tDtx3
29819152,妮玛士珍多,https://hbimg.huabanimg.com/ca4ecb573bf1ff0415c7a873d64470dedc465ea1213c6-RAkArS
19101282,陈勇敢❤,https://hbimg.huabanimg.com/ab6d04ebaff3176e3570139a65155856871241b58bc6-Qklj2E
28337572,爱意随风散,https://hbimg.huabanimg.com/117ad8b6eeda57a562ac6ab2861111a793ca3d1d5543-SjWlk2
17342758,幸运instant,https://hbimg.huabanimg.com/72b5f9042ec297ae57b83431123bc1c066cca90fa23-3MoJNj
18483372,Beau染,https://hbimg.huabanimg.com/077115cb622b1ff3907ec6932e1b575393d5aae720487-d1cdT9
22127102,栽花的小蜻蜓,https://hbimg.huabanimg.com/6c3cbf9f27e17898083186fc51985e43269018cc1e1df-QfOIBG
13802024,LoveHsu,https://hbimg.huabanimg.com/f720a15f8b49b86a7c1ee4951263a8dbecfe3e43d2d-GPEauV
22558931,白驹过隙丶梨花泪う,https://hbimg.huabanimg.com/e49e1341dfe5144da5c71bd15f1052ef07ba7a0e1296b-jfyfDJ
11762339,cojoy,https://hbimg.huabanimg.com/5b27f876d5d391e7c4889bc5e8ba214419eb72b56822-83gYmB
30711623,雪碧学长呀,https://hbimg.huabanimg.com/2c288a1535048b05537ba523b3fc9eacc1e81273212d1-nr8M4t
18906718,西霸王,https://hbimg.huabanimg.com/7b02ad5e01bd8c0a29817e362814666a7800831c154a6-AvBDaG
31037856,邵阳的小哥哥,https://hbimg.huabanimg.com/654953460733026a7ef6e101404055627ad51784a95c-B6OFs4
26830711,稳健谭,https://hbimg.huabanimg.com/51547ade3f0aef134e8d268cfd4ad61110925aefec8a-NKPEYX
# 练习题案例:下载文档中的所有图片且以用户名为图片名称存储。
import requests
import os
with open("mnv","r",encoding="utf-8") as csvfile:
    csvfile.readline()
    for line in csvfile:
        user_id,username,url=line.strip().split(",")
        # 1.根据URL下载图片
        res = requests.get(
            url=url,
            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"
            }
        )
        # 检查images目录是否存在?不存在,则创建images目录
        if not os.path.exists("images"):
            # 创建images目录
            os.makedirs("images")

        # 2.将图片的内容写入到文件
        with open("images/{}.png".format(username), mode='wb') as img_object:
            img_object.write(res.content)

ini格式文件

ini文件是Initialization File的缩写,平时用于存储软件的的配置文件。例如:MySQL数据库的配置文件
中括号括起来的叫节点
每个节点下面会有许多键值对和注释
比如这样

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
log-bin=py-mysql-bin
character-set-server=utf8
collation-server=utf8_general_ci
log-error=/var/log/mysqld.log
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid

[client]
default-character-set=utf8

open处理起来可以,但有些麻烦
python有更简单的办法:configparser

我们可以读取所有节点

import configparser

config = configparser.ConfigParser()
config.read('my.ini', encoding='utf-8')# 把文件读到内存了

ret = config.sections()
print(ret)# 输出 ['mysqld', 'mysqld_safe', 'client']

还可以输出一个节点下所有键值对组成的元组

import configparser

config = configparser.ConfigParser()
config.read('my.ini', encoding='utf-8')

result = config.items("mysqld")
print(result)#输出 [('datadir', '/var/lib/mysql'), ('socket', '/var/lib/mysql/mysql.sock'), ('log-bin', 'py-mysql-bin'), ('character-set-server', 'utf8'), ('collation-server', 'utf8_general_ci'), ('log-error', '/var/log/mysqld.log'), ('symbolic-links', '0')]

获取节点下的键对应的值

import configparser

config = configparser.ConfigParser()
config.read('my.ini', encoding='utf-8')

ret = config.sections()

result = config.get("mysqld","collation-server")
print(result) # 输出 utf8_general_ci

判断节点是否存在

v1 = config.has_section("client")
print(v1)

添加节点

config.add_section("group")# 添加节点,但这时只是加到内存里了,还没有写到文件里
# 需要把内容写到一个文件对象上,就是之前的open
config.write(open('new.ini', mode='w', encoding='utf-8'))

还可以添加键值

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'))

还可以删除节点

config.remove_section('client')#删除的同样是内存里的节点,还需要把内存里的内容写到文件里
config.remove_option("mysqld", "datadir")#删除节点的键值,指定节点和键
config.write(open('files/new.ini', mode='w', encoding='utf-8'))

XML格式文件

可扩展标记语言,是一种简单的数据存储语言,XML 被设计用来传输和存储数据。

  • 存储,可用来存放配置文件,例如:java的配置文件。
  • 传输,网络传输时以这种格式存在,例如:早期ajax传输的数据、soap协议等。

比如这样

<data>#开头
  <country name="Liechtenstein">#孩子标签开头
      <rank updated="yes">2</rank>#相当于一种字典套字典
      <year>2023</year>
      <gdppc>141100</gdppc>
      <neighbor direction="E" name="Austria" />
      <neighbor direction="W" name="Switzerland" />
  </country>#标签结尾
  <country name="Singapore">
      <rank updated="yes">5</rank>
      <year>2026</year>
      <gdppc>59900</gdppc>
      <neighbor direction="N" name="Malaysia" />
  </country>
  <country name="Panama">
      <rank updated="yes">69</rank>
      <year>2026</year>
      <gdppc>13600</gdppc>
      <neighbor direction="W" name="Costa Rica" />
      <neighbor direction="E" name="Colombia" />
  </country>
</data>#/代表结尾

同样python提供了操作该格式文件的xml.etree.ElementTree

读取

若是文件格式存在的xml

from xml.etree import ElementTree as ET

# ET去打开xml文件
tree = ET.parse("my.xml")

# 获取根标签
root = tree.getroot()

print(root) # <Element 'data' at 0x000002C5961F7F40>

若是以字符串形式存在的xml

from xml.etree import ElementTree as ET

content = """
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2023</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
     <country name="Panama">
        <rank updated="yes">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)
print(root)  #<Element 'data' at 0x0000028AFC6169A0>

获取子标签

from xml.etree import ElementTree as ET

content = """
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2023</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
     <country name="Panama">
        <rank updated="yes">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)
for child in root:
    print(child.tag, child.attrib)# 获取子标签及其属性
    for node in child:
        print(node.tag, node.attrib,node.text)#获取子标签里的子标签及其属性、内容
# country {'name': 'Liechtenstein'}
# rank {'updated': 'yes'} 2
# year {} 2023
# gdppc {} 141100
# neighbor {'direction': 'E', 'name': 'Austria'} None
# neighbor {'direction': 'W', 'name': 'Switzerland'} None
# country {'name': 'Panama'}
# rank {'updated': 'yes'} 69
# year {} 2026
# gdppc {} 13600
# neighbor {'direction': 'W', 'name': 'Costa Rica'} None
# neighbor {'direction': 'E', 'name': 'Colombia'} None

还有获取子标签的简单方法

country_object = root.find('country')#找到根标签下的第一个country
print(country_object.tag, country_object.attrib)#打印对应标签即属性
gdppc_object = country_object.find('gdppc')#还可以利用已经得到的子标签找其中的子标签
print(gdppc_object.tag, gdppc_object.attrib, gdppc_object.text)
# country {'name': 'Liechtenstein'}
# gdppc {} 141100

获取某些个标签

for child in root.iter("year"):
    print(child.tag, child.attrib, child.text)#输出year {} 2023
											  #    year {} 2026

找到所有标签

v1 = root.findall("country")
print(v1)
v2 = root.find("country").find("rank")
print(v2)
# [<Element 'country' at 0x000001EC1FBF7EF0>, <Element 'country' at 0x000001EC1FC251D0>]
# <Element 'rank' at 0x000001EC1FBF7F90>

修改、删除标签

修改

rank = root.find('country').find('rank')
print(rank.text)
rank.text = "999"#修改了rank标签的内容
rank.set('update', '2020-11-11')#增加了rank标签的属性
print(rank.text, rank.attrib)#以上这些修改都是在内存中完成的,还需要保存到文件中
############ 保存文件 ############
tree = ET.ElementTree(root)
tree.write("new.xml", encoding='utf-8')

以下为修改后的文档

<data>
    <country name="Liechtenstein">
        <rank updated="yes" update="2020-11-11">999</rank>
        <year>2023</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
     <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2026</year>
        <gdppc>13600</gdppc>
        <neighbor direction="W" name="Costa Rica" />
        <neighbor direction="E" name="Colombia" />
    </country>
</data>

删除也类似修改

# 删除节点
root.remove( root.find('country') )
print(root.findall('country'))


tree = ET.ElementTree(root)
tree.write("newnew.xml", encoding='utf-8')

删除了country节点后的文档

<data>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2026</year>
        <gdppc>13600</gdppc>
        <neighbor direction="W" name="Costa Rica" />
        <neighbor direction="E" name="Colombia" />
    </country>
</data>

构建文档

方法一

from xml.etree import ElementTree as ET

# 创建根标签
root = ET.Element("home")

# 创建节点大儿子
son1 = ET.Element('son', {'name': '儿1'})
# 创建小儿子
son2 = ET.Element('son', {"name": '儿2'})

# 在大儿子中创建两个孙子
grandson1 = ET.Element('grandson', {'name': '儿11'})
grandson2 = ET.Element('grandson', {'name': '儿12'})
son1.append(grandson1)
son1.append(grandson2)

# 把儿子添加到根节点中
root.append(son1)
root.append(son2)

tree = ET.ElementTree(root)
tree.write('abc.xml', encoding='utf-8', short_empty_elements=False)

short_empty_elements代表是否创建短标签,比如有些标签没有内容,那就可以用短标签表示,像<grandson name="儿11" />这样
效果如下

<home>
    <son name="儿1">
        <grandson name="儿11"></grandson>
        <grandson name="儿12"></grandson>
    </son>
    <son name="儿2"></son>
</home>

方法二

from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("famliy")


# 创建大儿子
son1 = root.makeelement('son', {'name': '儿1'})
# 创建小儿子
son2 = root.makeelement('son', {"name": '儿2'})

# 在大儿子中创建两个孙子
grandson1 = son1.makeelement('grandson', {'name': '儿11'})
grandson2 = son1.makeelement('grandson', {'name': '儿12'})

son1.append(grandson1)
son1.append(grandson2)


# 把儿子添加到根节点中
root.append(son1)
root.append(son2)

tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8')

方法三

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")

excel

利用第三方库openpyxl

获取sheet文件中的所有sheet名字

from openpyxl import load_workbook
wb = load_workbook('p1.xlsx')#读取到excel
print(wb.sheetnames)# 输出['数据导出', '用户列表', 'Sheet1', 'Sheet2']

excel中sheet如下
请添加图片描述

基于名称选择sheet

from openpyxl import load_workbook
wb = load_workbook('p1.xlsx')

sheet = wb['数据导出']#选择具体的一个sheet

cell = sheet.cell(1,1)选择一行一列单元格
print(cell.value)#输出该单元格的值

基于索引位置选择sheet

from openpyxl import load_workbook
wb = load_workbook('p1.xlsx')

sheet = wb.worksheets[0]#worksheets有所有sheet
cell = sheet.cell(row=1, column=2)
print(cell.value)

循环所有sheet

可以基于前两种找sheet的方法循环,也可以默认循环

for sheet in wb:
    cell = sheet.cell(1, 1)
    print(cell.value)

读sheet中单元格的信息

首先我们要知道一个sheet.cell里包含了很多包括字体、是否居中等信息

from openpyxl import load_workbook
wb = load_workbook('p1.xlsx')
sheet = wb.worksheets[0]
# 获取第n行m列的单元格
cell = sheet.cell(row=1, column=1)

print(cell.value)
print(cell.style)
print(cell.font)
print(cell.alignment)

# 常规
# <openpyxl.styles.fonts.Font object>
# Parameters:
# name='等线', charset=None, family=2.0, b=False, i=False, strike=None, outline=None, shadow=None, condense=None, color=<openpyxl.styles.colors.Color object>
# Parameters:
# rgb=None, indexed=8, auto=None, theme=None, tint=0.0, type='indexed', extend=None, sz=11.0, u=None, vertAlign=None, scheme='minor'
# <openpyxl.styles.alignment.Alignment object>
# Parameters:
# horizontal=None, vertical='center', textRotation=0, wrapText=None, shrinkToFit=None, indent=0.0, relativeIndent=0.0, justifyLastLine=None, readingOrder=0.0

获取某个单元格也可以利用excel的行列标志

c1 = sheet["A2"]
print(c1)
print(c1.value)

获取第n行所有单元格

行从1开始

print(sheet[1])#(<Cell '数据导出'.A1>, <Cell '数据导出'.B1>, <Cell '数据导出'.C1>, <Cell '数据导出'.D1>, <Cell '数据导出'.E1>, <Cell '数据导出'.F1>, <Cell '数据导出'.G1>, <Cell '数据导出'.H1>, <Cell '数据导出'.I1>, <Cell '数据导出'.J1>, <Cell '数据导出'.K1>)

由于是元组存储,故可以解包循环得到具体的值

for cell in sheet[1]:
    print(cell.value)

获取所有行

for row in sheet.rows:
    print(row[0].value)#获取所有行第一列

获取所有列

for col in sheet.columns:
    print(col[0].value)#读取第一行

读合并单元格

请添加图片描述
对于这样一个excel文件
如果读1行1列的内容,就是没合并的信息,如果读1行2列,就是合并的信息

sheet = wb.worksheets[2]
c1 = sheet.cell(row=1, column=1)
print(c1)#<Cell 'Sheet1'.A1>
print(c1.value)#用户信息

c2 = sheet.cell(row=1, column=2)
print(c2)#<MergedCell 'Sheet1'.B1>
print(c2.value)#None

以上这两个单元格类型不同
对垂直方向上也如此

for row in sheet.rows:
    print(row)
# (<Cell 'Sheet1'.A1>, <MergedCell 'Sheet1'.B1>, <Cell 'Sheet1'.C1>)
# (<Cell 'Sheet1'.A2>, <Cell 'Sheet1'.B2>, <Cell 'Sheet1'.C2>)
# (<Cell 'Sheet1'.A3>, <Cell 'Sheet1'.B3>, <Cell 'Sheet1'.C3>)
# (<MergedCell 'Sheet1'.A4>, <Cell 'Sheet1'.B4>, <Cell 'Sheet1'.C4>)
# (<Cell 'Sheet1'.A5>, <Cell 'Sheet1'.B5>, <Cell 'Sheet1'.C5>)

写excel

在原文件基础上写内容

from openpyxl import load_workbook

wb = load_workbook('p1.xlsx')
sheet = wb.worksheets[0]

# 找到单元格,并修改单元格的内容
cell = sheet.cell(1, 1)
cell.value = "新的开始"

# 将excel文件保存到p2.xlsx文件中
wb.save("p2.xlsx")

创建新文件写

from openpyxl import workbook

# 创建excel且默认会创建一个sheet(名称为Sheet)
wb = workbook.Workbook()

sheet = wb.worksheets[0] # 或 sheet = wb["Sheet"]

# 找到单元格,并修改单元格的内容
cell = sheet.cell(1, 1)
cell.value = "新的开始"

# 将excel文件保存到p2.xlsx文件中
wb.save("p2.xlsx")

具体如何写sheet

修改sheet名
from openpyxl import workbook

wb = workbook.Workbook()

sheet = wb.worksheets[0]

sheet.title = "数据集"
wb.save("p2.xlsx")
创建sheet并修改sheet颜色
sheet = wb.create_sheet("表格", 1)
sheet.sheet_properties.tabColor = "1072BA"#从rgb颜色对照表找
wb.save("p2.xlsx")

效果如下,出现了以表格命名的在1位置的sheet
请添加图片描述

默认打开的sheet
wb.active = 0#默认打开0位置的sheet
wb.save("p2.xlsx")
拷贝sheet
from openpyxl import workbook

wb = workbook.Workbook()

sheet = wb.create_sheet("表格",1)
sheet.sheet_properties.tabColor = "1072BA"

new_sheet = wb.copy_worksheet(wb["表格"])
new_sheet.title = "新的表格"
wb.save("p3.xlsx")
删除sheet
del wb["新的表格"]
wb.save('files/p2.xlsx')

具体如何写单元格

单个的内容操作同前
获取某些单元格并修改如下

from openpyxl import load_workbook
wb = load_workbook('p1.xlsx')
sheet = wb.worksheets[3]
cell_list = sheet["B2":"C3"]
#实际上cell_list是这样的:
#(
#	(单元格,单元格)#第一行
#	(单元格,单元格)#第二行
#)
for row in cell_list:
    for cell in row:
        cell.value = "a"
wb.save('p5.xlsx')

请添加图片描述

样式操作

接下来的操作需要先导入

from openpyxl.styles import Alignment,Border,Side,Font,PatternFill,GradientFill
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]

# 1. 获取某个单元格,修改值
"""
cell = sheet.cell(1, 1)
cell.value = "开始"
wb.save("p2.xlsx")
"""

# 2.  获取某个单元格,修改值
"""
sheet["B3"] = "Alex"
wb.save("p2.xlsx")
"""

# 3. 获取某些单元格,修改值
"""
cell_list = sheet["B2":"C3"]
for row in cell_list:
    for cell in row:
        cell.value = "新的值"
wb.save("p2.xlsx")
"""

# 4. 对齐方式
"""
cell = sheet.cell(1, 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)
wb.save("p2.xlsx")
"""

# 5. 边框
# side的style有如下:dashDot','dashDotDot', 'dashed','dotted','double','hair', 'medium', 'mediumDashDot', 'mediumDashDotDot','mediumDashed', 'slantDashDot', 'thick', 'thin'
"""
cell = sheet.cell(9, 2)
cell.border = Border(
    top=Side(style="thin", color="FFB6C1"), 
    bottom=Side(style="dashed", color="FFB6C1"),
    left=Side(style="dashed", color="FFB6C1"),
    right=Side(style="dashed", color="9932CC"),
    diagonal=Side(style="thin", color="483D8B"),  # 对角线
    diagonalUp=True,  # 左下 ~ 右上
    diagonalDown=True  # 左上 ~ 右下
)
wb.save("p2.xlsx")
"""

# 6.字体
"""
cell = sheet.cell(5, 1)
cell.font = Font(name="微软雅黑", size=45, color="ff0000", underline="single")
wb.save("p2.xlsx")
"""

# 7.背景色
"""
cell = sheet.cell(5, 3)
cell.fill = PatternFill("solid", fgColor="99ccff")
wb.save("p2.xlsx")
"""

# 8.渐变背景色
"""
cell = sheet.cell(5, 5)
cell.fill = GradientFill("linear", stop=("FFFFFF", "99ccff", "000000"))
##从左到右依次为渐变起始色,中间色,结束色
wb.save("p2.xlsx")
"""

# 9.宽高(索引从1开始)
"""
sheet.row_dimensions[1].height = 50#通过行设置高度
sheet.column_dimensions["E"].width = 100#通过列设置宽度
wb.save("p2.xlsx")
"""

# 10.合并单元格
"""
sheet.merge_cells("B2:D8")#合并方法一
sheet.merge_cells(start_row=15, start_column=3, end_row=18, end_column=8)#合并方法二
wb.save("p2.xlsx")
"""
"""
sheet.unmerge_cells("B2:D8")#接触合并方法一,同上还可以有二
wb.save("p2.xlsx")
"""

# 11.写入公式
"""
sheet = wb.worksheets[3]
sheet["D1"] = "合计"
sheet["D2"] = "=B2*C2"
wb.save("p2.xlsx")
"""
"""
sheet = wb.worksheets[3]
sheet["D3"] = "=SUM(B3,C3)"
wb.save("p2.xlsx")
"""

# 12.删除
"""
# idx,要删除的索引位置
# amount,从索引位置开始要删除的个数(默认为1)
sheet.delete_rows(idx=1, amount=20)#从第一行开始,往后20行都删掉
sheet.delete_cols(idx=1, amount=3)
wb.save("p2.xlsx")
"""

# 13.插入
"""
sheet.insert_rows(idx=5, amount=10)
sheet.insert_cols(idx=3, amount=2)
wb.save("p2.xlsx")
"""

# 14.循环写内容
"""
sheet = wb["Sheet"]
cell_range = sheet['A1:C2']
for row in cell_range:
    for cell in row:
        cell.value = "xx"

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"
wb.save("p2.xlsx")
"""

# 15.移动
"""
# 将H2:J10范围的数据,向右移动15个位置、向上移动1个位置
sheet.move_range("H2:J10",rows=-1, cols=15)
wb.save("p2.xlsx")
"""
"""
sheet = wb.worksheets[3]
sheet["D1"] = "合计"
sheet["D2"] = "=B2*C2"
sheet["D3"] = "=SUM(B3,C3)"
sheet.move_range("B1:D3",cols=10, translate=True) # 自动翻译公式
wb.save("p2.xlsx")
"""

# 16.打印区域
"""
sheet.print_area = "A1:D200"
wb.save("p2.xlsx")
"""

# 17.打印时,每个页面的固定表头
"""
sheet.print_title_cols = "A:D"
sheet.print_title_rows = "1:1"
wb.save("p2.xlsx")
"""

压缩文件

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')


# 2. 解压文件
"""
# filename,要解压的压缩包文件
# extract_dir,解压的路径
# format,压缩文件格式
"""
# shutil.unpack_archive(filename=r'datafile.zip', extract_dir=r'xxxxxx/xo', format='zip')

路径相关

import os

abs = os.path.abspath(__file__)#获取当前文件所在路径
print(abs)#C:\Users\24480\AppData\Roaming\JetBrains\PyCharm2023.3\light-edit\01\luffy\fuction\路径相关.py
path = os.path.dirname(abs)#获取上一级路径
print(path)#C:\Users\24480\AppData\Roaming\JetBrains\PyCharm2023.3\light-edit\01\luffy\fuction

有了上一级路径,我们可以利用此打开同一级其他文件

import os

base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = base_dir+"\天下之主.txt"

f= open(file_path, "r", encoding="gbk")
print(f.read())
f.close()

但由于斜杠的原因,不同操作系统会受影响,故还要优化
把文件名拼接方法os.path.join加入

import os

base_dir = os.path.dirname(os.path.abspath(__file__))
# file_path = base_dir+"\天下之主.txt"
file_path = os.path.join(base_dir, '天下之主.txt')
print(file_path)
#C:\Users\24480\AppData\Roaming\JetBrains\PyCharm2023.3\light-edit\01\luffy\fuction\天下之主.txt
if os.path.exists(file_path):#还可以先判断文件是否存在
    f= open(file_path, "r", encoding="gbk")
    print(f.read())
    f.close()
else:
    print("文件不存在")
import shutil
import os

# 1. 获取当前脚本绝对路径
"""
abs_path = os.path.abspath(__file__)
print(abs_path)
"""

# 2. 获取当前文件的上级目录
"""
base_path = os.path.dirname( os.path.dirname(路径) )
print(base_path)
"""

# 3. 路径拼接
"""
p1 = os.path.join(base_path, 'xx')
print(p1)

p2 = os.path.join(base_path, 'xx', 'oo', 'a1.png')
print(p2)
"""

# 4. 判断路径是否存在
"""
exists = os.path.exists(p1)
print(exists)
"""

# 5. 创建文件夹
"""
os.makedirs(路径)
"""
"""
path = os.path.join(base_path, 'xx', 'oo', 'uuuu')
if not os.path.exists(path):
    os.makedirs(path)
"""

# 6. 是否是文件夹
"""
file_path = os.path.join(base_path, 'xx', 'oo', 'uuuu.png')#有后缀名的创建文件
is_dir = os.path.isdir(file_path)
print(is_dir) # False

folder_path = os.path.join(base_path, 'xx', 'oo', 'uuuu')#无后缀名的创建文件夹
is_dir = os.path.isdir(folder_path)
print(is_dir) # True

"""

# 7. 删除文件或文件夹
"""
os.remove("文件路径")
"""
"""
path = os.path.join(base_path, 'xx')
shutil.rmtree(path)
"""

# 8. 拷贝文件夹
"""
shutil.copytree("/Users/wupeiqi/Desktop/图/csdn/","/Users/wupeiqi/PycharmProjects/CodeRepository/files")
"""

# 9.拷贝文件
"""
shutil.copy("/Users/wupeiqi/Desktop/图/csdn/WX20201123-112406@2x.png","/Users/wupeiqi/PycharmProjects/CodeRepository/")
shutil.copy("/Users/wupeiqi/Desktop/图/csdn/WX20201123-112406@2x.png","/Users/wupeiqi/PycharmProjects/CodeRepository/x.png")
"""

# 10.文件或文件夹重命名
"""
shutil.move("/Users/wupeiqi/PycharmProjects/CodeRepository/x.png","/Users/wupeiqi/PycharmProjects/CodeRepository/xxxx.png")
shutil.move("/Users/wupeiqi/PycharmProjects/CodeRepository/files","/Users/wupeiqi/PycharmProjects/CodeRepository/images")
"""
  • 19
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值