简体   繁体   English

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

[英]Swapping lines in text with unknown lines using Python

I have 5 big text files, and I want to copy only one line from one of the files, and replace the same lines in the other files.我有 5 个大文本文件,我只想从其中一个文件中复制一行,并替换其他文件中的相同行。 Each line starts the same, only the end is different, and the line is unique.每一行的开头都一样,只有结尾不同,而且行是唯一的。

After browsing many options, this is what I got now (for one of the files):浏览了许多选项后,这就是我现在得到的(对于其中一个文件):

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 = " is the identifier for the line that needs to be changed, the value from fileNumberOne is the correct one, and I need to swap the value for fileNumberTwo, and the line is unique so no need to worry about getting suddenly 2 lines that include the words "FUSE_ROOT_DIR". "FUSE_ROOT_DIR = "是需要修改的那一行的标识符,fileNumberOne的值是正确的,我需要交换fileNumberTwo的值,而且该行是唯一的,所以不用担心突然出现2行包括“FUSE_ROOT_DIR”字样。

The result is that the line won't change, and also the first line in fileNumberTwo is deleted (it starts with ###, maybe it has something to do with it?).结果是这一行不会改变,并且fileNumberTwo中的第一行也被删除了(它以###开头,可能与它有关?)。

Any ideas?有任何想法吗?

Thanks!谢谢!

an illustration of my comment: you could do it in two steps, eg我的评论的说明:您可以分两步完成,例如

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

Another option for step #2 would be to use the fileinput module to do the replacement "in-place":第 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())

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

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