从txt文件中删除特定行
所以我的问题是:我正在Discord机器人上使用Python(使用discord.py). 但是,我希望机器人读取txt文件,从其中选择一行,然后再删除该行. 这是我走了多远:
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()
您需要将这些行写回到文件中.否则,您只是在修改局部变量.要对同一个文件对象执行此操作,则需要在写入前将seek
移至文件的开头.您可能还需要使用行列表,例如从readlines
开始,而不是在编写它们时遍历这些行.然后,您可以truncate
最后没有写的任何其他行.
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.
有关读写文件和I/O的更多信息,请参见 https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files 和
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.
此外,在您的代码中,您正在隐藏readlist
和内置的list
.
这也与discord.py或Discord机器人无关.
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.