删除文件中的一行 [英] Deleting a line in a file

查看:66
本文介绍了删除文件中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用timetracker程序时遇到问题,在该程序中,我试图通过遍历文件然后在其内写行来标识文件中的一行,除非其中包含变量"delete"(由于某种原因)浏览文件并说它已删除,但是循环并没有删除任何行.

I am having an issue with a timetracker program, where I am trying to identify a line in a file by iterating over it and then writing the lines UNLESS there is anything with the variable "delete" in it, for some reason its going through the file and saying it is deleted, but the loop doesn't delete any lines.

date = input(" What is today's date? month-day-year format please. (E.G. 01-14-2003) ")
if os.path.exists(date):
    today = open(date, "r")
    print(today.read())

    delete = input(" Which appointment would you like to delete? (Please type the time E.G. 7:00) ")

    #Open the file, save the read to a variable, iterate over the file, check to see if the time is what user entered, if it is not then write it to the line, close the file.

    fileEdit = open(date, "r+")
    for line in today.readline():
        print(line)
        if delete not in line:
            fileEdit.write(line)
    print(fileEdit.read())
    today.close()
    fileEdit.close()
    print ("Appointment deleted, goodbye")

推荐答案

这正在读取到文件末尾

print(today.read())

在这里开始迭代时,您已经结束了

When you start iterating here, you're already at the end

for line in today.readline():

因此永远不会输入for循环.您需要重新打开文件或返回到开头.

so the for loop will never be entered. You need to reopen the file or seek back to the beginning.

另一个问题是您要遍历第一行.你可能是说

Another problem is that you are iterating over the first line. You probably meant

for line in today:

无论如何,写一个与您正在读取的文件通常不是一个好主意(例如,考虑到如果计算机在途中被重置,文件将陷入混乱)

Regardless, it's generally not a great idea to write to the same file you are reading (eg. consider the mess the file would be in if the computer gets reset partway through)

最好写一个临时文件并替换.

Better to write a temporary file and replace.

如果文件很小,则可以将其读入内存列表中,然后再次将其重写.

If the files are very small, you could read the file into a list in memory and then rewrite the file out again.

一个更好的主意是,在深入之前,是使用数据库,例如sqlite模块(内置于Python)

A better idea, before you go too far is to use a database such as the sqlite module (which is builtin to Python)

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

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