从txt文件中删除特定行 [英] Delete a specific line from txt file

查看:114
本文介绍了从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.

这篇关于从txt文件中删除特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆