简体   繁体   English

如何使用索引删除文本文件python中的特定行?

[英]How to delete a specific line in text file python using indices?

for example i have this text file: subj.txt and it contains the texts below (subject|time) 例如我有这个文本文件:subj.txt它包含下面的文本(主题|时间)

astro1|1:00-2:00
act2|2:00-3:00
speech1|4:00-5:00

Btw, i'm using tkinter to create a gui. 顺便说一句,我正在使用tkinter创建一个gui。 when a button is clicked, a window with text entry will appear and the program will ask the user to input what course will be deleted. 单击按钮时,将出现带有文本输入的窗口,程序将要求用户输入将删除的课程。 So when a user selects astro1 and the button is clicked, the astro1 will be deleted in the textfile and the ac2 and speech 2 will go up. 因此,当用户选择astro1并单击该按钮时,将在文本文件中删除astro1,并且ac2和语音2将上升。 What is the code for that? 那是什么代码?

For example I have an entrybox with name self.courseent and i have a function below for the button: 例如,我有一个名为self.courseent的入口箱,我在下面有一个按钮功能:

f=open("subj.txt",'r') 
  for x in f:
   a=x.split('|') 
   if self.courseent.get()==a[0]: 
     #the line where the a[0] will be deleted

You question look a lot like this question : 你的问题看起来很像这个问题:

How to delete a line from a text file in C#? 如何从C#中的文本文件中删除一行?

Actually file doesn't allow you to simply delete a line from a file. 实际上,文件不允许您简单地从文件中删除一行。 What you have to do is to read the all file in memory as an list, delete the line from the list and re-open the file in write mode and rewrite everything. 你要做的是将内存中的所有文件作为列表读取,从列表中删除该行并在写入模式下重新打开文件并重写所有内容。 If you file is too big to be loaded in memory, you should write to an other file and then copy your temporary inside your file. 如果文件太大而无法加载到内存中,则应写入其他文件,然后将临时文件复制到文件中。

https://docs.python.org/2/library/tempfile.html https://docs.python.org/2/library/tempfile.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM