Python;我们如何复制一个txt文件中的随机行并删除同一行?

Python; How do we copy a random line in a txt file and delete the same line?

我们有 2 个 txt 文件。 (file1.txtfile2.txt)

我想将 file1.txt 中的随机行分配给名为 x 的变量,并且 我希望从 file1.txt 中删除此随机行并在新行中添加到 file2.txt

如果file1.txt里面什么都没有,我想把[=里面的所有行都复制过来47=]丢进file1.txt,删除file2.txt中的所有行。 然后我想将 file1.txt 中的随机行分配给名为 x 的变量。 我希望从 file1.txt 中删除此随机行并在新行中添加到 file2.txt

我只能 select 随机行并将它们分配给 x。

import random
from random import randint

file=open("file1.txt","r")
rows=file.readlines()
i=0
m={}
for row in rows:
    m[i]=row
    i=i+1
print(i)
random_row_number= random.randint(0,i)
x=m[random_row_number]
file.close()
import os
import random


def do_your_random_line_thing(from_file, to_file):
    with open(from_file, "r") as f1:
        rows = f1.readlines()
        random_line_number = random.randint(0, len(rows) - 1)
        random_line_content = rows.pop(random_line_number)
    with open(from_file, "w") as f1:
        f1.writelines(rows)
    with open(to_file, "a") as f2:
        f2.write(random_line_content)


def copy_from_one_to_another(f, t):
    with open(f) as f:
        lines = f.readlines()
        with open(t, "w") as f1:
            f1.writelines(lines)


file_1 = r"file1.txt"
file_2 = r"file2.txt"

if os.path.getsize(file_1) == 0:
    copy_from_one_to_another(file_2, file_1)
    open(file_2, 'w').close()  # delete file_2 content

do_your_random_line_thing(file_1, file_2)