替换文本文件中的字符串

时间:2015-11-18 10:31:05

标签: python

我写了一个脚本,打开我的文本文件搜索某个单词,然后选择包含这个单词的行,将它分成三个部分,然后选择一个数字部分并加1,所以每次我运行脚本时都会添加一个这个号码。这是脚本:

#!/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()

但我的问题是新号码正在写在文件的末尾,我希望它保留在原来的位置。有什么想法吗?

感谢

3 个答案:

答案 0 :(得分:0)

问题是你在原始文件之后写了新版本号(没有版本行):

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

您可以通过单独保存包含该版本的行之前和之后的行来修复它,然后按正确的顺序保存它们:

#!/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()

注意:您可能需要在版本行中添加一些额外的文本,以使其具有与原始格式相同的格式(例如添加“_PATCH”)。

答案 1 :(得分:0)

您的代码有很多话要说。

您的错误在于您正在编写“已保存”的行并在编写修改后的版本之后。因此,这条修改过的行将写在文件的末尾。

此外,我建议您使用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)

此代码未经测试,可能包含一些错误...另外,如果您的输入文件很大,将每行放在列表中可能是个坏主意。

答案 2 :(得分:0)

#!/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()

如果找到某个行,更新其内容并添加到saved,一旦for循环结束,只需将saved写入文件