0

我有一个包含多行的 .txt 文件(每一行都不同但相似),我想在最后添加一个“* .tmp”。

我正在尝试使用 python2.7 正则表达式来做到这一点。

这是我对 python 脚本的内容:

import sys
import os
import re
import shutil

#Sets the buildpath variable to equal replace one "\" with two "\\" for python code to input/output correctly
buildpath = sys.argv[1]
buildpath = buildpath.replace('\\', '\\\\')

#Opens a tmp file with read/write/append permissions
tf = open('tmp', 'a+')

#Opens the selenium script for scheduling job executions
with open('dumplist.txt') as f:
#Sets line as a variable for every line in the selenium script
    for line in f.readlines():
    #Sets build as a variable that will replace the \\build\path string in the line of the selenium script
        build = re.sub (r'\\\\''.*',''+buildpath+'',line)
        #Overwrites the build path string from the handler to the tmp file with all lines included from the selenium script
        tf.write(build)
#Saves both "tmp" file and "selenium.html" file by closing them
tf.close()
f.close()
#Copies what was re-written in the tmp file, and writes it over the selenium script
shutil.copy('tmp', 'dumplist.txt')
#Deletes the tmp file
os.remove('tmp')
#exits the script
exit()

更换线路前的当前文件:

\\server\dir1\dir2\dir3

DUMP3f2b.tmp   
           1 File(s)  1,034,010,207 bytes

\\server\dir1_1\dir2_1\dir3_1

DUMP3354.tmp   
           1 File(s)    939,451,120 bytes

\\server\dir1_2\dir2_2\dir3_2

替换字符串后的当前文件:

\*.tmp

DUMP3f2b.tmp   
           1 File(s)  1,034,010,207 bytes

\*.tmp

DUMP3354.tmp   
           1 File(s)    939,451,120 bytes

\*.tmp

替换字符串后所需的文件:

\\server\dir1\dir2\dir3\*.tmp

DUMP3f2b.tmp   
           1 File(s)  1,034,010,207 bytes

\\server\dir1_1\dir2_1\dir3_1\*.tmp

DUMP3354.tmp   
           1 File(s)    939,451,120 bytes

\\server\dir1_2\dir2_2\dir3_2\*.tmp

如果有人可以帮助我解决这个问题,那就太好了。谢谢 :)

4

1 回答 1

1

您应该使用捕获组:

>>> import re
>>> s = "\\server\dir1\dir2\dir3"
>>> print re.sub(r'(\\.*)', r'\\\1\*.tmp', s)
\\server\dir1\dir2\dir3\*.tmp

然后,build = re.sub (r'\\\\''.*',''+buildpath+'',line)以这种方式修改行:

build = re.sub (r'(\\.*)', r'\\\1%s' % buildpath, line)

此外,您不应该调用readlines(),只需迭代f

for line in f:
于 2013-08-29T22:00:48.250 回答