简体   繁体   English

python:我想搜索一行并替换一行

[英]python: I want to search a line and replace a line

I want to search a line and replace a line in a file.txt,我想搜索一行并替换 file.txt 中的一行,

CURRENT_BUILD = 111111

with

CURRENT_BUILD = 221111

Using Python.使用 Python。

You can iterate through the lines in the file, saving them to a list and then output the list back to the file, line by line, replacing the line if necessary:您可以遍历文件中的行,将它们保存到list ,然后将列表逐行输出回文件,必要时替换该行:

with open('file.txt') as f:
    lines = f.readlines()

with open('file.txt', 'w+') as f:
    for line in lines:
        if line == 'CURRENT_BUILD = 111111\n':
            f.write('CURRENT_BUILD = 221111\n')
        else:
            f.write(line)
CURRENT_BUILD = '111111'
print (CURRENT_BUILD.replace('111111', '221111'))

The syntax of replace() is: replace() 的语法是:

str.replace(old, new [, count])

old - old substring you want to replace old - 要替换​​的旧子字符串

new - new substring which would replace the old substring new - 将替换旧子字符串的新子字符串

count (optional) - the number of times you want to replace the old substring with the new substring count ( 可选) - 用新子串替换旧子串的次数

If count is not specified, replace() method replaces all occurrences of the old substring with the new substring.如果未指定计数,replace() 方法将用新子字符串替换所有出现的旧子字符串。

I'm not sure if this is what you meant as you are unclear and haven't shown what the .txt file is but this is replace anyways.我不确定这是否是您的意思,因为您不清楚并且没有显示 .txt 文件是什么,但这无论如何都是替换。

EDIT编辑

if it is in text replace you want then this would be your best bet.如果它是您想要的文本替换,那么这将是您最好的选择。

import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
    print(line.replace(text_to_search, replacement_text), end='')

credit to @jfs from this post How to search and replace text in a file using Python?归功于这篇文章中的@jfs 如何使用 Python 搜索和替换文件中的文本?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM