Search code examples
pythonrandomlinefile-writingfile-read

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


We have 2 txt files. (file1.txt and file2.txt)

I want a random row in file1.txt to be assigned to the variable named x and I want this random line to be deleted from file1.txt and added to file2.txt in a new line.

If there is nothing in file1.txt, I want to copy all lines in file2.txt and throw them into file1.txt and delete all lines in file2.txt. And then I want a random row in file1.txt to be assigned to the variable named x. I want this random line to be deleted from file1.txt and added to file2.txt in a new line.

I was only able to select random rows and assign them to 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()

Solution

  • 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)