简体   繁体   English

如何用另一个文件中的文本替换一个文件中的文本?

[英]How to replace text in one file with text from another file?

I am trying to put text from a file in another file that also contains text.我正在尝试将一个文件中的文本放入另一个也包含文本的文件中。 Example:例子:

FILE 1 contains:文件 1 包含:

@WORLD

FILE 2 contains:文件 2 包含:

HELLO:LEARNING

I would like to insert the content of FILE1 into FILE2 to get:我想将FILE1的内容插入FILE2得到:

HELLO@WORLD:LEARNING

More or less I have the code:或多或少我有代码:

fname = input("Put your file: ")

if fname == "combos.txt":
    try:
        f = open(fname) #OPEN THE FILE "COMBOS.TXT"
        delimiter = ":"
        with open("combos.txt", "r", encoding='UTF-8')as f: #WITH THE FILE "COMBOS.TXT" OPENED AS VARIABLE F
            data = [f"{x}{delimiter}{y}" for x,y in [tuple(i.strip().split(delimiter)) for i in f.readlines()]] #

            with open("lowercase - combos.txt", "w+", encoding='UTF-8')as f:
                f.write("\n".join(data))
                
            input("Your file was edited successfully! Press enter to continue...")
        
        if platform.system() == "Windows":
            p = subprocess.call(["python", "start.py"])
    except:
        print("--Something went wrong while trying to load your file--")

The problem is in this part:问题出在这部分:

data = [f"{x}{delimiter}{y}" for x,y in [tuple(i.strip().split(delimiter)) for i in f.readlines()]] #

x and y are the text from FILE 2: HELLO (X): LEARNING (Y) xy是文件 2 中的文本: HELLO (X): LEARNING (Y)

And I would like to add the text from FILE 1 --> @WORLD to FILE 2 in (X):我想将FILE 1 --> @WORLD中的文本添加到 (X) 中的 FILE 2:

HELLO@WORLD (X): LEARNING (Y) HELLO@WORLD (X): LEARNING (Y)

I don´t know how to fix it, I suppose that is editing variable X .我不知道如何修复它,我想那是编辑变量X I made different test (creating a variable to open the other file, or putting write() function. Not worked me, I don´t know if more or less is something like that but I couldn´t do it):我做了不同的测试(创建一个变量来打开另一个文件,或者把write() function。我没用,我不知道是否或多或少是这样的,但我做不到):

data = [f"{x}{delimiter}{y}"

IIUC, you want to create the new data to be in the format of: IIUC,您希望创建的新数据格式如下:

{X from FILE2}{FILE 1}:{Y from FILE2}

Currently in your code I see that you only loop on a single file.目前在您的代码中,我看到您只在一个文件上循环。 You should loop on both files simultanasouly, using the zip function. Then simply construct your data:您应该使用zip function 同时循环处理这两个文件。然后简单地构造您的数据:

with open(FILE1) as file1, open(FILE2) as file2:
    data = []
    for line1, line2 in zip(file1, file2):
        x, y = line2.split(':')
        data.append(f"{x}{line1.strip()}:{y}")

with open(FILE2, 'w') as file2:
    file2.writelines(data)

Note that you usually don't need to use readlines()/read() and create unnecessary lists/strings in memory for most file operations.请注意,对于大多数文件操作,您通常不需要使用readlines()/read()并在 memory 中创建不必要的列表/字符串。 You can just loop in-place directy on the lines of the file ( for line in file ) as files are iterators in Python.您可以直接在文件的行上就地循环( for line in file ),因为文件是 Python 中的迭代器。

Unsure of what you are wanting as the process of this program.不确定你想要什么作为这个程序的过程。 I did come up with a result on my end matching your expectations.最后我确实得出了符合您期望的结果。 Validation is not provided, that is up to you.不提供验证,这取决于您。

# file1.txt = @WORLD
# file2.txt = HELLO:LEARNING
# file2.txt after run = HELLO@WORLD:LEARNING

def insert_file_in_file(f1_path, f2_path, placed_before = " "):
    with open(f1_path, "r") as f1:
        f1_text = f1.read()
    with open(f2_path, "r") as f2:
        f2_text = f2.read()

    with open(f2_path, "w") as f2:
        string_list = f2_text.split(placed_before)
        f2.write((f1_text + placed_before).join(string_list))

insert_file_in_file("file1.txt", "file2.txt", ":")

暂无
暂无

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

相关问题 将一个文本文件中的值替换为另一个 - Replace value from one text file into another 如何使用Python搜索和替换文本从一个文件到另一个文件? - How to search and replace text from one file to another using Python? 如何将多列从一个文本文件替换为另一文本文件中的列? - How to replace multi-column from one text file to a column in another text file? 仅当某些值相等时,如何才能将一个文本文件中的值替换为另一文本文件中的其他值? - How can I replace values from one text file with other values from another text file only if certain values are equal? 如何在另一个文本文件中的Y行中查找和替换一个文本文件中的X行? - How to find and replace X lines in one text file with Y lines in another text file? 从另一个文本文件替换文本文件中的行 - replace lines in a text file from another text file 如何使用一个文本文件中的字符串搜索另一个文本,并使用另一个文本列创建一个新的文本文件? - How to use strings from one text file to search another, and create a new text file with columns from another? 从另一个文本文件中提取一个文本文件中的句子 - Extracting the sentences from one text file from another text file 使用python从一个文本文件中查找短语在另一个文本文件中 - Find phrases from one text file in another text file with python 从另一个文本文件中的一个文本文件中过滤单词? - filter words from one text file in another text file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM