mercredi 27 novembre 2019

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. Delete this random line from file1.txt and delete it from file2.txt I want it to be added to 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()



Aucun commentaire:

Enregistrer un commentaire