使用Python将文本中的行与未知行交换

阿萨夫·罗克尼

我有 5 个大文本文件,我只想从其中一个文件中复制一行,并替换其他文件中的相同行。每一行的开头都一样,只有结尾不同,而且行是唯一的。

浏览了许多选项后,这就是我现在得到的(对于其中一个文件):

with open(fileNumberOne) as f1:
    for line1 in f1:
        if "FUSE_ROOT_DIR = " in line1:
            with open(fileNumberTwo) as f2:
                for line2 in f2:
                    newText = f2.read()
                    if "FUSE_ROOT_DIR = " in line2in :
                        newText = f2.read().replace(line2in , line1)
                    with open(fileNumberTwo, "w") as f2:
                        f2.write(newText)

"FUSE_ROOT_DIR = "是需要修改的那一行的标识符,fileNumberOne的值是正确的,我需要交换fileNumberTwo的值,而且该行是唯一的,所以不用担心突然出现2行包括“FUSE_ROOT_DIR”字样。

结果是这一行不会改变,并且fileNumberTwo中的第一行也被删除了(它以###开头,可能与它有关?)。

有任何想法吗?

谢谢!

弗普斯先生

我的评论的说明:您可以分两步完成,例如

token = 'FUSE_ROOT_DIR '
with open(file1, 'r') as fobj: # 1 - find your "reference" line
    for line in fobj:
        if token in line:
            ref_line = line
            break # skip the rest of the lines

if ref_line: # 2 - if it was found, replace it in the other files  
    with open(file2, 'r+') as fobj: # loop this for all your other files
        content = fobj.readlines() # read everything to a variable and modify that
        content = [ref_line if token in l else l for l in content]
        fobj.seek(0) # reset file pointer to beginning of file
        fobj.writelines(content) # overwrite with modified content

第 2 步的另一个选择是使用fileinput模块进行“就地”替换:

import fileinput        

with fileinput.input(file2, inplace=True) as f:
    for line in f:   
        if token in line:
            line = ref_line
        print(line.strip())

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章