python - 文件操作(xml/yaml/ini/txt)

文件操作

访问方式说明
r以只读方式打开文件。文件的指针将会放在文件的开头,这是默认模式。如果文件不存在,抛出异常
w以只写方式打开文件。如果文件存在会被覆盖。如果文件不存在,创建新文件
a以追加方式打开文件。如果该文件已存在,文件指针将会放在文件的结尾。如果文件不存在,创建新文件进行写入
r+以读写方式打开文件。文件的指针将会放在文件的开头。如果文件不存在,抛出异常
w+以读写方式打开文件。如果文件存在会被覆盖。如果文件不存在,创建新文件
a+以读写方式打开文件。如果该文件已存在,文件指针将会放在文件的结尾。如果文件不存在,创建新文件进行写入

文件/目录的常用管理操作

在 终端 / 文件浏览器、 中可以执行常规的 文件 / 目录 管理操作,例如:

os 模块

  • 创建、重命名、删除、改变路径、查看目录内容、……

文件操作

序号方法名说明示例
01rename重命名文件os.rename(源文件名, 目标文件名)
02remove删除文件os.remove(文件名)

目录操作

序号方法名说明示例
01listdir目录列表os.listdir(目录名)
02mkdir创建目录os.mkdir(目录名)
03rmdir删除目录os.rmdir(目录名)
04getcwd获取当前目录os.getcwd()
05chdir修改工作目录os.chdir(目标目录)
06path.isdir判断是否是文件os.path.isdir(文件路径)

提示:文件或者目录操作都支持 相对路径 和 绝对路径

Shutil 模块

作为os模块的补充,提供了复制、移动、删除、压缩、解压等操作

序号方法名说明
01shutil.copy(src, dst)复制文件
02shutil.copytree(src, dst)复制文件夹
03shutil.move(src, dst)移动文件或文件夹
04shutil.rmtree(src, dst)删除文件夹 (不能删除文件)

zipfile 模块

zipfile是python的一个内置模块,供了通用的创建、读取、写入、附加和显示压缩文件的方法。

import zipfile
zip_file_path = 'Collections_study.zip'
python_file = 'test.py'
'''将当前目录下的 test.py 拷贝到压缩包中'''
with zipfile.ZipFile(zip_file_path, 'a') as f:
     f.write(python_file)

''' 获取压缩包中某个文件的信息'''
with zipfile.ZipFile(zip_file_path, 'r') as f:
    # <ZipInfo filename='test.py' filemode='-rw-rw-rw-' file_size=154>
    print(f.getinfo(python_file))
    '''查看压缩包内的文件信息'''
    print(f.infolist())
    '''获取zip文档内所有文件的名称列表'''
    print(f.namelist())
    '''将zip文档内的指定文件解压到当前目录'''
    f.extractall()
    '''解压单个文件'''
    f.extract(python_file)

文件读取和写入

ini 文件操作

在Python中通过ConfigParser模块对ini进行读写操作,常用方法有:

    读操作
    read(filename) 读取文件内容(当配置文件有中文时,在调用read()方法时,需要传encoding="utf-8-sig"参数 
    sections() 获取所有的section,以列表形式返回
    options(section)  获取指定section的所有options,以列表形式返回
    items(section)  获取指定section的所有键值对,以列表形式返回
    get(section, option)  获取指定option的值,返回类型string
    
   
    写操作
    write(fp) 将config对象写入ini文件
    add_section(section) 添加一个新的section
    set(section, option, value) 对指定section下的某个option赋值
    remove_section(section) 删除某个section
    remove_option(section, option) 删除某个section下的某个option
# -*- coding: utf-8 -*-
# description: ini 文件处理

import configparser


class dispose_ini:
    """
    封装一个类,进行ini文件的常用操作
    """

    def __init__(self, filepath):
        self._path = filepath
        self.config = configparser.ConfigParser()  # 实例化解析对象
        self.config.read(filepath, encoding='utf-8')  # 读文件
        print('---config: ', self.config)

    def get_sections(self):
        """
        获取ini文件所有的块,返回为list
        """
        sect = self.config.sections()
        return sect

    def get_options(self, sec):
        """
        获取ini文件指定块的项
        :param sec: 传入的块名
        :return: 返回指定块的项(列表形式)
        """
        return self.config.options(sec)

    def get_items(self, sec):
        """
        获取指定section的所有键值对
        :param sec: 传入的块名
        :return: section的所有键值对(元组形式)
        """
        return self.config.items(sec)

    def get_option(self, sec, opt):
        """
        :param sec: 传入的块名
        :param opt: 传入项
        :return: 返回项的值(string类型)
        """
        return self.config.get(sec, opt)

    def write_(self):
        """ 将修改后写入文件 """
        with open(self._path, 'w') as fp:
            self.config.write(fp)

    def add_section_(self, sec):
        """
        为ini文件添加新的section, 如果section 已经存在则抛出异常
        :param sec: 传入的块名
        :return: None
        """
        self.config.add_section(sec)
        self.write_()

    def set_option(self, sec, opt, value):
        """
        对指定section下的某个option赋值
        :param sec: 传入的块名
        :param opt: 传入的项名
        :param value: 传入的值
        :return:  None
        """
        self.config.set(sec, opt, value)
        self.write_()  # 写入文件

    def remove_sec(self, sec):
        """
        删除某个section
        :param sec: 传入的块名
        :return: bool
        """
        self.config.remove_section(sec)
        self.write_()  # 写入文件

    def remove_opt(self, sec, opt):
        """
        删除某个section下的某个option
        :param sec: 传入的块名
        :param opt: 传入的项名
        :return: bool
        """
        self.config.remove_option(sec, opt)
        self.write_()  # 写入文件


if __name__ == '__main__':
    # 加载文件, 初始化
    dis = dispose_ini('.\demo.ini')

    # 获取ini文件所有的section
    print(dis.get_sections())

    # 获取指定section的所有options
    print(dis.get_options('s_name'))

    # 获取指定section的所有键值对
    print(dis.get_items('s_name'))

    # 获取指定section指定option的值
    print(dis.get_option('s_name', 'stu4'))

    # 对指定option赋值
    dis.set_option('s_name', 'stu7', '88')

    # 删除指定section
    dis.remove_sec('s_title')

    # 增加section
    dis.add_section_('s_title')

    # 删除指定option
    dis.remove_opt('s_name', 'stu7')

Yaml 文件操作

# 1. 对象:yaml键值对:即python中字典
usr: my
psw: 123455
s: " abc\n"
#解析后:{'usr': 'my', 'psw': 123455, 's': ' abc\n'}

# 2. 数组:yaml键值对中嵌套数组
usr3:
 - a
 - b
 - c
usr4:
 - b
#解析后:{'usr3': ['a', 'b', 'c'], 'usr4': ['b']}

# 3. 纯量
s_val: name       # 字符串:{'s_val': 'name'}
spec_s_val: "name\n"  # 特殊字符串:{'spec_s_val': 'name\n'
num_val: 31.14     # 数字:{'num_val': 31.14}
bol_val: true      # 布尔值:{'bol_val': True}
nul_val: null      # null值:{'nul_val': None}
nul_val1: ~       # null值:{'nul_val1': None}
time_val: 2018-03-01t11:33:22.55-06:00   # 时间值:{'time_val': datetime.datetime(2018, 3, 1, 17, 33, 22, 550000)}
date_val: 2019-01-10  # 日期值:{'date_val': datetime.date(2019, 1, 10)}

# 4. 引用
name: &name 灰蓝
tester: *name
# 相当于
name: 灰蓝
tester: 灰蓝
#解析后内容:{'name': '灰蓝', 'tester': '灰蓝'}

# 5. 强制转换
str: !!str 3.14
int: !!int "123"
# 输出:{'int': 123, 'str': '3.14'}

Yaml 操作

https://www.jb51.net/article/184299.htm

Yaml 内容

# yaml键值对嵌套:即python中字典嵌套字典
usr1:
  name: a
  psw: 123
usr2:
  name: b
  psw: 456

读取Yaml

import yaml
import os
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "test.yaml")
file = open(yaml_path, 'r', encoding="utf-8")
file_data = file.read() #读取file内容
file.close()

print(type(file_data))
print(file_data)

'''转化为字典'''
data = yaml.load(file_data) #转换为字典类型
print(type(data))
print(data)

写入Yaml

# 将python对象生成yaml文档
import os
import yaml

def generate_yaml_doc(yaml_file):
  py_object = {'school': 'zhang',
         'students': ['a', 'b']}
  file = open(yaml_file, 'w', encoding='utf-8')
  yaml.dump(py_object, file, sort_keys=False, default_flow_style=False)
  file.close()

current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "generate.yaml")
generate_yaml_doc(yaml_path

XML 操作

XML即可扩展标记语言,XML是互联网数据传输的重要工具,它可以跨越互联网任何的平台,不受编程语言和操作系统的限制,可以说它是一个拥有互联网最高级别通行证的数据携带者。

import xml.etree.ElementTree as ET

root = ET.Element('root')
class1 = ET.SubElement(root, 'class')
student1 = ET.SubElement(class1, 'student')
student1.set('id', '1')
student1.set('name', 'gavin')


tree = ET.ElementTree(root)

tree.write('simple.xml', encoding='utf-8', xml_declaration=True)

链接: https://www.cnblogs.com/lizexiong/p/16686203.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值