栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Python中覆盖文件中的字符

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Python中覆盖文件中的字符

使用fileinput和

inplace=True
修改文件内容:

import fileinputimport sysfor line in fileinput.input("test.txt",inplace=True):    # replaces all occurrences of apples in each line with oranges    sys.stdout.write(line.replace("apples","oranges"))

输入:

Marry has 10 carrotsBob has 15 applesTom has 4 bananas

输出:

Marry has 10 carrotsBob has 15 orangesTom has 4 bananas

使用re避免匹配子字符串:

import fileinputimport sysimport re# use word boundaries so we only match "apples"  r = re.compile(r"bapplesb")for line in fileinput.input("test.txt",inplace=True):    # will write the line as is or replace apples with oranges and write    sys.stdout.write(r.sub("oranges",line))

删除所有遗留词:

import fileinputimport sysfor line in fileinput.input("test.txt",inplace=True):    # split on the last whitespace and write everything up to that    sys.stdout.write("{}n".format(line.rsplit(None, 1)[0]))

输出:

Marry has 10Bob has 15Tom has 4

您还可以使用tempfile.NamedTemporaryFile使用以上任何逻辑将更新后的行写入,然后使用shutil.move替换原始文件:

from tempfile import NamedTemporaryFilefrom shutil import movewith open("test.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:    for line in f:        temp.write("{}n".format(line.rsplit(None, 1)[0]))# replace original file with updated contentmove(temp.name,"test.txt")

您需要通过

dir="."
delete=False
因此当我们退出with时,文件文件不会被删除,我们可以使用
.name
属性访问该文件以传递给shutil。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/653560.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号