从txt文件中删除特定行

时间:2019-12-26 19:00:17

标签: python file

所以我的问题是:我正在Discord机器人上使用Python(使用discord.py)。 但是,我希望机器人读取txt文件,从其中选择一行并在此之后删除该行。 这是我走了多远:

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

1 个答案:

答案 0 :(得分:0)

您需要将这些行写回到文件中。否则,您只是在修改局部变量。要对同一个文件对象执行此操作,则需要在写入之前seek至文件的开头。您可能还需要使用行列表,例如从readlines开始,而不是在编写时遍历所有行。然后,您可以truncate结束时未写的任何其他行。

有关读写文件和I / O的更多信息,请参见https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-fileshttps://docs.python.org/3/library/io.html

此外,在您的代码中,您正在遮盖readlistthe built-in list
这也与discord.py或Discord机器人无关。

相关问题