“Python文本处理”的版本间的差异

来自CloudWiki
跳转至: 导航搜索
第83行: 第83行:
  
 
当tmp.txt追加新的内容时,新内容会被程序立即打印出来。
 
当tmp.txt追加新的内容时,新内容会被程序立即打印出来。
 +
===大文件读写===
 +
普通的小文件读写:
 +
 +
  <nowiki>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')</nowiki>
  
 
对大文件进行读写:
 
对大文件进行读写:
第95行: 第108行:
  
 
===读写配置文件===
 
===读写配置文件===
 +
配置文件是供程序运行时读取配置信息的文件,用于将配置信息与程序分离,这样做的好处是显而易见的:例如在开源社区贡献自己源代码时,将一些敏感信息通过配置文件读取;提交源代码时不提交配置文件可以避免自己的用户名、密码等敏感信息泄露;我们可以通过配置文件保存程序运行时的中间结果;
 +
 +
Python内置的配置文件解析器模块configparser提供ConfigParser类来解析基本的配置文件,我们可以使用它来编写Python程序,让用户最终通过配置文件轻松定制自己需要的Python应用程序。
 +
 +
建立ini文件:
 +
 +
<nowiki>"""
 +
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)
 +
</nowiki>
 +
 +
读取ini文件:
 +
 +
<nowiki># 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]}]")  # 打印键和值
 +
</nowiki>
 +
 +
写入ini文件:
 +
 +
<nowiki># 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())
 +
</nowiki>
 
===读写XML文件===
 
===读写XML文件===

2020年2月5日 (三) 10:39的版本

Python编码解码

# -*- coding: utf-8 -*-
# 本文件应该保存为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}"')
byte1 = str.encode("gbk")
print(f'Unicode字符串"{str}"以gbk编码得到字节串[{byte1}]')
str1 = byte1.decode("gbk")
print(f'将gbk字节串[{byte1}]解码得到Unicode字符串"{str1}"')

print(f'以文本方式将Unicode字符串"{str}"写入a.txt')

with open("a.txt", "w", encoding="gbk") as f:
    f.write(str)

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

Python文件读写

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

f = open("wb.txt", "w", encoding="utf-8")
f.write("测试w方式写入,如果文件存在,则清空内容后写入,如果文件不存在则创建\n")
f.close()

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

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

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

例:在文件中定位

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

f = open("tmp.txt", "rb+")
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('tmp.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('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文件:

# 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文件