0

So my problem is: I am working with Python on a Discord bot (using discord.py). However, I want the bot to read a txt file, choose one line out of it and delete this line after that. This is how far I've come:

list = open(r"C:\Users\Max\Documents\Python\Discord Bots\Test File\Text\text.txt","r+")
readlist = list.readlines()
text = random.choice(readlist)
for readlist in list:     <-- I guess there is the problem
    readlist = "\n"       <-- here too
list.close()
Harmon758
  • 5,084
  • 3
  • 22
  • 39
  • `readlist` is already defined as the output of `list.readlines()` you will need to use a different variable in your for loop – Joel Trauger Dec 26 '19 at 19:14

1 Answers1

0

You need to write the lines back to the file. Otherwise, you're just modifying the local variable. To do this with the same file object, you'll need to seek to the beginning of the file before you write. You'll probably also want to use a list of lines, e.g. from readlines, rather than iterating through the lines while you're writing them. You can then truncate any additional lines you didn't write over at the end.

For more information about reading and writing files and I/O, see https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files and https://docs.python.org/3/library/io.html.

Also, in your code, you're shadowing readlist and the built-in list.
This also has nothing to do with discord.py or Discord bots.

Harmon758
  • 5,084
  • 3
  • 22
  • 39
  • Thank you very much, would you be able to write me the corrected code? :)) – NoCoconut Anymore Dec 26 '19 at 19:45
  • You should see [the question this one has now been marked a duplicate of](https://stackoverflow.com/questions/4710067/using-python-for-deleting-a-specific-line-in-a-file) for examples. – Harmon758 Dec 26 '19 at 19:47
  • 1
    @NoCoconutAnymore You seem to think that SO is a SW service where you give the problem, you ask for the code and we give you the code, but unfortunately (fortunately) it is not the objective of the site to do so. Follow the guides we have offered you, understand them, try them and clearly indicate where you are stuck to help you. We will not give you code but an answer. – eyllanesc Dec 26 '19 at 23:05