Python文本处理

来自CloudWiki
跳转至: 导航搜索

Python编码解码

utf-8编码:

str = "我是中国人"
print(f'Unicode字符串为"{str}"')
byte0 = str.encode("utf-8")
print(f'Unicode字符串"{str}"以utf-8编码得到字节串[{byte0}]')
str0 = byte0.decode("utf-8")
print(f'将utf-8字节串[{byte0}]解码得到Unicode字符串"{str0}"')


gbk编码:



byte1 = str.encode("gbk")
print(f'Unicode字符串"{str}"以gbk编码得到字节串[{byte1}]')
str1 = byte1.decode("gbk")
print(f'将gbk字节串[{byte1}]解码得到Unicode字符串"{str1}"')


Python文件读写

读写方式

f = open("maxin.txt","读写格式",encoding="编码")

f.read()/f.write()

f.close()

读写格式:

‘r’:只读。该文件必须已存在。

‘r+’:可读可写。该文件必须已存在,写为追加在文件内容末尾。

‘rb’:表示以二进制方式读取文件。该文件必须已存在。

‘w’:只写。打开即默认创建一个新文件,如果文件已存在,则覆盖写(即文件内原始数据会被新写入的数据清空覆盖)。

‘w+’:写读。打开创建新文件并写入数据,如果文件已存在,则覆盖写。

‘wb’:表示以二进制写方式打开,只能写文件, 如果文件不存在,创建该文件;如果文件已存在,则覆盖写。

‘a’:追加写。若打开的是已有文件则直接对已有文件操作,若打开文件不存在则创建新文件,只能执行写(追加在后面),不能读。

‘a+’:追加读写。打开文件方式与写入方式和'a'一样,但是可以读。需注意的是你若刚用‘a+’打开一个文件,一般不能直接读取,因为此时光标已经是文件末尾,除非你把光标移动到初始位置或任意非末尾的位置。

w:清空写入

# -*- coding: utf-8 -*-

f = open("maxin.txt","w",encoding="utf-8")
f.write("我爱自动化运维.\n")
f.write("我爱网络行业..\n")
f.write("hello world\n")
f.close()


a: 追加写入

f = open("maxin.txt", "a", encoding="utf-8")
f.write("测试a方式写入,如果文件存在,在文件内容后最后追加写入,如果文件不存在则创建")
f.close()

t: 以文本形式读文件

f = open("maxin.txt", "rt", encoding="utf-8")
# 以文本方式读,f.read()返回字符串对象
data = f.read()
print(type(data))
print(data)
f.close()

b: 以字节形式读文件

f = open("maxin.txt", "rb")
# 以文本方式读,f.read()返回字节对象
data = f.read()
print(type(data))
print(data)
print('将读取的字符对象解码:')
print(data.decode('utf-8'))
f.close()

简约写法

简约写法 的好处是 可以不用担心 f.close() 忘了写的问题。

print(f'以文本方式将Unicode字符串"{str}"写入a.txt')
str="简约写法 的好处是 可以不用担心 f.close() 忘了写的问题"
with open("maxin.txt", "a", encoding="utf-8") as f:
    f.write(str)

print("以文本方式读取 maxin.txt 的内容")
with open("maxin.txt", "r", encoding="utf-8") as f:
    print(f.read())

文件定位

seek() 方法语法如下:

fileObject.seek(offset[, whence])

参数

   offset -- 开始的偏移量,也就是代表需要移动偏移的字节数
   whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。

例:在文件中定位

# -*- coding: utf-8 -*-
# !/usr/local/bin/python
# Time: 2018/5/23 22:56:26
# Description:
# File Name: seek_file.py

f = open("maxin.txt", "wb+")
f.write(b"abcdefghi")
f.seek(5)  # 移动到文件的第六个字节
print(f.read(1))
f.seek(-3, 2)  # 移动到文件的倒数第三字节
print(f.read(1))

例:基于seek实现类似Linux命令tail -f的功能(文件名为lx_tailf.py)

# encoding=utf-8

import time

with open('maxin.txt', 'rb') as f:
    f.seek(0, 2)  # 将光标移动至文件末尾
    while True:  # 实时显示文件新增加的内容
        line = f.read()
        if line:
            print(line.decode('utf-8'), end='')
        else:
            time.sleep(0.2)  # 读取完毕后短暂的睡眠


当tmp.txt追加新的内容时,新内容会被程序立即打印出来。

共享文档:可将上述程序改写为共享文档?在一端修改了之后,另一端马上呈现?

特殊读写操作

大文件读写

普通的小文件读写:

 小文件读写的思路是读取文件全部内容、存到字符串变量里,然后把字符串写入原文件。
 import os
with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
    data=read_f.read()
    data=data.replace('str1','str2')
    write_f.write(data)
     

os.remove('a.txt')

os.rename('.a.txt.swap','a.txt')

对大文件进行读写:

 大文件读写的思路是对文件内容进行逐行操作,防止内存溢出。

大文件读:

import os
with open(r'd:/maxin.txt',encoding="utf-8") as read_f:
     for line in read_f:#对可迭代对象f逐行操作,防止内存溢出
          print(line)

大文件写:

import os
with open('a.txt',encoding="utf-8") as read_f,open('.a.txt.swap','w',encoding="utf-8") as write_f:
     for line in read_f:#对可迭代对象f逐行操作,防止内存溢出
          line=line.replace('中国人','Chinese')
          write_f.write(line)
os.remove('a.txt')
os.rename('.a.txt.swap','a.txt')

读写配置文件

配置文件是供程序运行时读取配置信息的文件,用于将配置信息与程序分离,这样做的好处是显而易见的:例如在开源社区贡献自己源代码时,将一些敏感信息通过配置文件读取;提交源代码时不提交配置文件可以避免自己的用户名、密码等敏感信息泄露;我们可以通过配置文件保存程序运行时的中间结果;

Python内置的配置文件解析器模块configparser提供ConfigParser类来解析基本的配置文件,我们可以使用它来编写Python程序,让用户最终通过配置文件轻松定制自己需要的Python应用程序。

建立ini文件:

"""
python建立pip.ini.py
2016年4月30日 03:35:11 codegay
"""

import os

ini="""[global]
index-url = https://pypi.doubanio.com/simple/
[install]
trusted-host=pypi.doubanio.com
"""
pippath=os.environ["USERPROFILE"]+"\\pip\\"

if not os.path.exists(pippath):
    os.mkdir(pippath)

with open(pippath+"pip.ini","w+") as f:
    f.write(ini)

读取ini文件:

# encoding=utf-8
import os
import configparser
pippath=os.environ["USERPROFILE"]+"\\pip\\"
config = configparser.ConfigParser()  # 实例化ConfigParser类

config.read(pippath+r"pip.ini")  # 读取配置文件

for section in config.sections():  # 首先读取sections
    print(f"section is [{section}]")
    for key in config[section]:  # 讲到每个section的键和值
        print(f"key is [{key}], value is [{config[section][key]}]")  # 打印键和值

写入ini文件:


import os
import configparser
config =configparser.ConfigParser()
config["global"]={
    "index-url":"https://pypi.doubanio.com/simple/",
    
}
config["install"]={
    "trusted" :"pypi.doubanio.com",
    }

with open("example.ini", "w") as configfile: #将上述配置信息config写入文件example.ini
    config.write(configfile)

例子2:

# encoding=utf-8
import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {
    "ServerAliveInterval": "45",
    "Compression": "yes",
    "CompressionLevel": "9",
}
config["bitbucket.org"] = {}
config["bitbucket.org"]["User"] = "hg"
config["topsecret.server.com"] = {}
topsecret = config["topsecret.server.com"]
topsecret["Port"] = "50022"  # mutates the parser
topsecret["ForwardX11"] = "no"  # same here
config["DEFAULT"]["ForwardX11"] = "yes"
#print(type(config["DEFAULT"].getboolean('Compression')))
#print(config["bitbucket.org"]['ServerAliveInterval'])
with open("example.ini", "w") as configfile: #将上述配置信息config写入文件example.ini
    config.write(configfile)

with open("example.ini", "r") as f: #读取example.ini 验证上述写入是否正确
    print(f.read())

读写XML文件

文件1.xml

<breakfast_menu year="2018">
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>
two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>
light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>
light Belgian waffles covered with an assortment of fresh berries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>
thick slices made from our homemade sourdough bread
</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>
two eggs, bacon or sausage, toast, and our ever-popular hash browns
</description>
<calories>950</calories>
</food>
</breakfast_menu>

代码:

import xml.etree.ElementTree as ET

tree = ET.parse("1.xml")
root = tree.getroot()
print(f"这是一个早餐菜单\n{root.attrib['year']}")

for child in root:
    print("name:", child[0].text)
    print("price:", child[1].text)
    print("description:", child[2].text)
    print("calories:", child[3].text)