搜索特定字符串,仅将字符串的一部分复制到另一个文本文件中

时间:2013-04-08 19:18:55

标签: python string file search

我希望我的python程序在文本文件中搜索字符串的特定部分。 例如,我的文本文件如下所示:

VERSION_1_0001
VERSION_2_0012
VERSION_3_0391

这些只是一些例子。我希望我的python程序查找“VERSION_2_”,但让它在另一个文本文件中打印出0012。这可能吗?

到目前为止我只有这个:

with open('versions.txt', 'r') as verFile:
    for line in verFile:
        if 'VERSION_2_' in line:
            ??? (I don't know what would go here so I can get the portion attached to the string I'm finding)

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

如果您的问题是关于如何在最后一个下划线之后提取行的部分:

 with open('versions.txt', 'r') as verFile:
    for line in verFile:
        if 'VERSION_2_' in line:
            # Split the line from the right on underscores and
            # take the last part of the resulting list.
            print line.rpartition('_')[-1]

如果您的问题是关于写入文件:

with open('resultfile', 'w') as wFile:
    wFile.write(line.rpartition('_')[-1])

如果要将所有结果写入同一文件,请在循环外打开要写入的文件:

# It doesn't matter which `with` block is the outermost.
with open('resultfile', 'w') as wFile:
    with open('versions.txt', 'r') as verFile:
        for line in verFile:
            if 'VERSION_2_' in line:
                # Split the line from the right on underscores and
                # take the last part of the resulting list.
                wFile.write(line.rpartition('_')[-1])