I have been messing around with python for fun and I want to know how to remove a random name from a text file that contains a list of names (ex Lst1.txt) and inset it to a new text file of the names removed (Lst2.txt) so that every time I run the function it updates both files. I have a .py file that does this for 2 lists that are defined in the file. I want to have this use files for when I have to turn off the computer and have to relaunch the .py file
So for example if Lst1.txt has the names "John Smith, Jane Doe, John Johnson" and I run the function it would then pick a random name, remove it from Lst1.txt, and add it to Lst2.txt
Then Lst1.txt would then be "John Smith, John Johnson", And Lst2.txt would be "Jane Doe".
When the last name from Lst1.txt is selected, the file would be empty while Lst2.txt would be "Jane Doe, John Smith, John Johnson"
CodePudding user response:
The question seems to center around "how can I select a random item from a list?"
Lists can be indexed (starting from 0
). So select a random index and grab the item at that index.
>>> from random import randint
>>> lst = ["foo", "bar", "baz"]
>>> lst[randint(0, len(lst) - 1)]
'baz'
>>> item = lst[randint(0, len(lst)- 1)]
>>> item
'baz'
>>> lst.remove(item)
>>> lst
['foo', 'bar']
>>>
Removing a random item from one list and adding to another:
>>> lst = ["foo", "bar", "baz"]
>>> lst2 = []
>>> while lst:
... item = lst[randint(0, len(lst)- 1)]
... lst.remove(item)
... lst2.append(item)
...
>>> lst
[]
>>> lst2
['foo', 'baz', 'bar']
>>>
CodePudding user response:
One thing that you can do is store the names of the 1st file in a list, and using random.choice()
take a random value out of it, and write it to the 2nd file and append the remaining to the 1st file like this...
from random import choice
from time import time
start = time()
with open("sample1.txt") as Rf1:
data = Rf1.read().split(",")
name = choice(data)
Wf1, Wf2 = open("sample1.txt", "w"), open("sample2.txt", "w")
Wf2.write(data.pop(data.index(name)))
Wf1.write(",".join(data))
Wf1.close(); Wf2.close()
end = time()
print(f"Executed in {end-start} secs")
Output:-
Executed in 0.0007908344268798828 secs