蟒蛇;我们如何在txt文件中复制随机行并删除同一行?

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

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

如果 file1.txt 中没有任何内容,我想复制 file2.txt 中的所有行并将其放入 file1.txt ,并删除 file2.txt 中的所有行。 然后,我想将 file1.txt 中的随机行分配给名为x的变量。 我希望从 file1.txt 中删除此随机行,并在新行中将其添加到 file2.txt 中。

我只能选择随机行并将它们分配给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()
jasonzhuhello 回答:蟒蛇;我们如何在txt文件中复制随机行并删除同一行?

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)
本文链接:https://www.f2er.com/3018589.html

大家都在问