python 替换txt文件中的整行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2527435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace a whole line in a txt file
提问by user302935
I'am new to Python 3 and could really use a little help. I have a txt file containing:
我是 Python 3 的新手,真的可以使用一些帮助。我有一个 txt 文件,其中包含:
InstallPrompt=
DisplayLicense=
FinishMessage=
TargetName=D:\somewhere
FriendlyName=something
I have a python script that in the end, should change just two lines to:
我有一个 python 脚本,最后应该只将两行更改为:
TargetName=D:\new
FriendlyName=Big
Could anyone help me, please? I have tried to search for it, but I didnt find something I could use. The text that should be replaced could have different length.
请问有人可以帮我吗?我试图搜索它,但我没有找到我可以使用的东西。应该替换的文本可以有不同的长度。
采纳答案by Dan Story
A very simple solution for what you're doing:
您正在做的事情的一个非常简单的解决方案:
#!/usr/bin/python
import re
import sys
for line in open(sys.argv[1],'r').readlines():
line = re.sub(r'TargetName=.+',r'TargetName=D:\new', line)
line = re.sub(r'FriendlyName=.+',r'FriendlyName=big', line)
print line,
You would invoke this from the command line as ./test.py myfile.txt > output.txt
您可以从命令行调用它 ./test.py myfile.txt > output.txt
回答by ghostdog74
import fileinput
for line in fileinput.FileInput("file",inplace=1):
sline=line.strip().split("=")
if sline[0].startswith("TargetName"):
sline[1]="new.txt"
elif sline[0].startswith("FriendlyName"):
sline[1]="big"
line='='.join(sline)
print(line)
回答by John La Rooy
Writing to a temporary file and the renaming is the best way to make sure you won't get a damaged file if something goes wrong
写入临时文件并重命名是确保出现问题时不会损坏文件的最佳方法
import os
from tempfile import NamedTemporaryFile
fname = "lines.txt"
with open(fname) as fin, NamedTemporaryFile(dir='.', delete=False) as fout:
for line in fin:
if line.startswith("TargetName="):
line = "TargetName=D:\new\n"
elif line.startswith("FriendlyName"):
line = "FriendlyName=Big\n"
fout.write(line.encode('utf8'))
os.rename(fout.name, fname)
回答by Dan Story
Is this a config (.ini) file you're trying to parse? The format looks suspiciously similar, except without a header section. You can use configparser
, though it may add extra space around the "=" sign (i.e. "TargetName=D:\new
" vs. "TargetName = D:\new
"), but if those changes don't matter to you, using configparser
is way easier and less error-prone than trying to parse it by hand every time.
这是您要解析的配置 (.ini) 文件吗?除了没有标题部分之外,格式看起来非常相似。您可以使用configparser
,尽管它可能会在“=”符号周围添加额外的空间(即“ TargetName=D:\new
”与“ TargetName = D:\new
”),但是如果这些更改对您来说无关紧要,则使用configparser
比尝试解析更容易且不易出错每次都用手。
txt (ini) file:
txt(ini)文件:
[section name]
FinishMessage=
TargetName=D:\something
FriendlyName=something
Code:
代码:
import sys
from configparser import SafeConfigParser
def main():
cp = SafeConfigParser()
cp.optionxform = str # Preserves case sensitivity
cp.readfp(open(sys.argv[1], 'r'))
section = 'section name'
options = {'TargetName': r'D:\new',
'FriendlyName': 'Big'}
for option, value in options.items():
cp.set(section, option, value)
cp.write(open(sys.argv[1], 'w'))
if __name__ == '__main__':
main()
txt (ini) file (after):
txt(ini)文件(之后):
[section name]
FinishMessage =
TargetName = D:\new
FriendlyName = Big
回答by jfs
subs_names.py
script works both Python 2.6+ and Python 3.x:
subs_names.py
脚本适用于 Python 2.6+ 和 Python 3.x:
#!/usr/bin/env python
from __future__ import print_function
import sys, fileinput
# here goes new values
substitions = dict(TargetName=r"D:\new", FriendlyName="Big")
inplace = '-i' in sys.argv # make substitions inplace
if inplace:
sys.argv.remove('-i')
for line in fileinput.input(inplace=inplace):
name, sep, value = line.partition("=")
if name in substitions:
print(name, sep, substitions[name], sep='')
else:
print(line, end='')
Example:
例子:
$ python3.1 subs_names.py input.txt
InstallPrompt=
DisplayLicense=
FinishMessage=
TargetName=D:\new
FriendlyName=Big
If you are satisfied with the output then add -i
parameter to make changes inplace:
如果您对输出感到满意,请添加-i
参数以进行原地更改:
$ python3.1 subs_names.py -i input.txt