0

我在使用 timetracker 程序时遇到问题,我试图通过对其进行迭代来识别文件中的一行,然后编写这些行,除非其中有任何带有变量“delete”的东西,出于某种原因,它会通过文件并说它已被删除,但循环不会删除任何行。

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")
4

4 回答 4

2

这是读取到文件末尾

print(today.read())

当你在这里开始迭代时,你已经到了最后

for line in today.readline():

所以永远不会进入for循环。您需要重新打开文件或回到开头。

另一个问题是您正在迭代第一行。你可能是说

for line in today:

无论如何,写入您正在阅读的同一个文件通常不是一个好主意(例如,考虑如果计算机在中途重置,文件将处于混乱状态)

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

如果文件非常小,您可以将文件读入内存中的列表,然后再次将文件重写。

在你走得太远之前,一个更好的主意是使用诸如sqlite模块之类的数据库(内置于 Python)

于 2013-11-06T21:09:03.680 回答
1

today.readline()返回单行。for-loop 遍历该行中的字符。正如@gnibbler 指出的那样,today文件在被调用时位于文件的末尾today.readline()(因此它返回一个空字符串)。

通常,要删除文件中间的某些内容,您需要完全替换该文件。fileinput模块可以帮助:

import fileinput

for line in fileinput.input([date], inplace=1):
    if delete not in line:
       print line, # stdout is redirected to the `date` file

这里几乎相同,但没有fileinput

import os
from tempfile import NamedTemporaryFile

filename = date
dirpath = os.path.dirname(filename)
with open(filename) as file, NamedTemporaryFile("w", dir=dirpath) as outfile:
    for line in file:
        if delete not in line:
           print >>outfile, line, # copy old content
    outfile.delete = False # don't delete outfile
os.remove(filename) # rename() doesn't overwrite on Windows
os.rename(outfile.name, filename) # or just `os.replace` in Python 3.3+
于 2013-11-06T21:16:23.303 回答
1

问题来自读取和写入同一个文件。这是对此的一些解释。

很好的参考(Beginner Python: Reading and writing to the same file

因此,在r+模式下,对文件的读取和写入都会将文件指针向前移动。

所以让我们看看你的例子。首先你做一个readline。这会将文件指针移动到下一行。你检查你刚刚读到的那行是否有效,如果是,就写出来。

问题是你只是覆盖了下一行,而不是前一行!所以你的代码真的把你的数据弄乱了。

基本上,想要做正确的事情真的很难(如果文件很大,效率也会很低)。您不能随意删除文件中间的字节。对于您要删除的每一行,您必须在其上写入其余数据,然后在末尾截断文件以删除释放的空间。

您应该听取其他答案的建议,然后输出到另一个文件或stdout.

于 2013-11-06T21:25:48.773 回答
0

好吧,您还可以执行以下操作:

with open("input.txt",'r') as infile, open("output.txt",'w') as outfile: 
    # code here

    outfile.write(line)

在您的文件循环中,您可以执行以下操作:

if delete:
   continue

跳过您不想写入输出文件的行。

于 2013-11-06T21:13:05.250 回答