简体   繁体   English

替换文本文件中的字符串

[英]replacing a string in a text file

I wrote a script that will open my text file search for a certain word, then select the line that contains this word ans split it into three parts, then it chooses the part which is a number and add 1 to it, so every time I run the script one is added to this number. 我写了一个脚本,它将打开我的文本文件以搜索某个单词,然后选择包含该单词的行并将其分成三部分,然后选择数字部分并将其加1,因此每次运行脚本一个被添加到该编号。 here is the script: 这是脚本:

#!/usr/bin/env python
inputFile = open('CMakeLists.txt', 'r')

version = None
saved = ""

for line in inputFile:
    if "_PATCH " in line:
        print "inside: ", line
        version = line

    else:
        saved += line

inputFile.close()

inputFile = open('CMakeLists.txt', 'w')

x = version.split('"')
print "x: ", x

a = x[0]
b = int(x[1]) + 1
c = x[2]

new_version = str(a) + '"' + str(b) + '"' + str(c)
print "new_version: ", new_version

inputFile.write(str(saved))
inputFile.write(str(new_version))

inputFile.close()

but my problem is that the new number is being written at the end of the file, I want it to stay in its original place. 但是我的问题是新编号正在文件的末尾写入,我希望它保留在其原始位置。 Any ideas ? 有任何想法吗 ?

thanks 谢谢

The problem is that you write the new version number after the original file (without the version line): 问题是您将新版本号写在原始文件之后(没有版本行):

inputFile.write(str(saved))
inputFile.write(str(new_version))

You could fix it by saving the lines before and after the line that contains the version separately and then save them in the right order: 您可以通过以下方式解决此问题:分别保存包含版本的行之前和之后的行,然后以正确的顺序保存它们:

#!/usr/bin/env python
inputFile = open('CMakeLists.txt', 'r')

version = None
savedBefore = ""
savedAfter = ""

for line in inputFile:
    if "_PATCH " in line:
        print "inside: ", line
        version = line
    elif version is None:
        savedBefore += line
    else:
        savedAfter += line

inputFile.close()

inputFile = open('CMakeLists.txt', 'w')

x = version.split('"')
print "x: ", x

a = x[0]
b = int(x[1]) + 1
c = x[2]

new_version = str(a) + '"' + str(b) + '"' + str(c)
print "new_version: ", new_version

inputFile.write(savedBefore)
inputFile.write(str(new_version))
inputFile.write(savedAfter)

inputFile.close()

Note: you might need to add some extra text with the version line to make it have the same format as the original (such as adding "_PATCH"). 注意:您可能需要在版本行中添加一些额外的文本,以使其具有与原始格式相同的格式(例如添加“ _PATCH”)。

There is a lots to say on your code. 您的代码有很多要说的。

Your mistake is that you're writing your "saved" lines and after you are writing your modified version. 您的错误是您正在编写“已保存”行,并且在编写修改后的版本之后。 Hence, this modified line will be written at the end of the file. 因此,此修改的行将被写入文件的末尾。

Moreover, I advice you to use with statements. 此外,我建议您使用with语句。

lines = []    
with open('CmakeLists.txt', 'r') as _fd:
    while True:
        line = _fd.readline()
        if not line:
            break
        if '_PATCH ' in line:
            a, b, c = line.split('"')
            b = int(b) + 1
            line = '{} "{}" {}'.format(a, b, c)
        lines.append(line)
with open('CmakeLists.txt', 'w') as _fd:
    for line in lines:
        _fd.write(line)

This code is untested and may contains some error... also, if your input file is huge, putting every lines in a list can be a bad idea. 此代码未经测试,可能包含一些错误...此外,如果您的输入文件很大,则将每一行都放在列表中可能是个坏主意。

#!/usr/bin/env python
inputFile = open('CMakeLists.txt', 'r')

version = None
saved = ""

for line in inputFile:
    if "_PATCH " in line:
        print "inside: ", line
        version = line
        x = version.split('"')
        print "x: ", x

        a = x[0]
        b = int(x[1]) + 1
        c = x[2]

        new_version = str(a) + '"' + str(b) + '"' + str(c)
        saved += new_version
    else:
        saved += line

inputFile.close()

inputFile = open('CMakeLists.txt', 'w')
inputFile.write(str(saved))

inputFile.close()

if a certain line is found, update its content and add to saved , once for loop ends, just write saved to file 如果找到某行,则更新其内容并添加到saved ,一旦for循环结束,只需将saved写入文件

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

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