繁体   English   中英

当满足某些条件时,如何使此for循环正常工作以替换文件中的行?

[英]How can I get this for loop to work correctly to replace a line in a file when certain conditions are met?

我正在寻找一个图书馆类型的程序,该程序允许您从一个小的“数据库”文本文件中取出一本书,然后修改文件中的行,以包括先前输入的用户ID以表明它已被使用。

输入的用户ID必须是一个整数,且必须为4位数字,这使我可以使用try / except程序来进行处理,但现在开始实际写入文件时,似乎不再跑过去询问book_id,尽管它在我检查ID正确长度的所有内容之前都起作用。

同样,所有这些都应该放在“ def checkout()”函数中(这样我以后就可以对一个主程序进行修改,包括我编写的搜索功能和一个允许您“退还”书的程序),但是如果我尝试放下它在其中,我得到的都是缩进错误,每当我尝试使用中断以阻止程序重复“对不起,找不到书ID或书不可用”时,每本书或每本书都会死。 在这一点上,我只是在寻找基本功能,即使它不能完美运行,所以主要的优先任务是使其真正运行。

while True:
    txt = open("book_list.txt", "r+")
    try:
         user_id = int((raw_input("Please enter your ID: ")))
         if len(str(user_id)) != 4:
            print "Sorry, that was an invalid ID. Please try again."
            continue
         break
    except:
       print "Sorry, that was an invalid ID. Please try again."

book_id = (raw_input("Please enter the book ID no. you would like to take out: "))

for line in txt:
         if book_id == line[0] and line[-1] == " ":
                txt.write(line.replace(line,user_id))
                print "You have successfully taken out the book."

         else:
                print "Sorry, either the book ID was not found or the book is unavailable."



txt.close()

有问题的文本文件是:

1 Book_1 Author_1 1234
2 Book_1 Author_1 
3 Book_2 Author_2 
4 Book_3 Author_3 2000
5 Book_4 Author_3 

书籍ID是左侧的数字,而用户ID(或空格“”表示该书籍可用)是右侧的数字。

我可能很简单,因为我是一个初学者,所以我很想念它并使其无法工作,但我感谢任何投入,欢呼。

首先,您可以轻松地验证ID,而无需使用异常:

def id_valid(id):
    return len(id) == 4 and id.isdigit()

如果字符串中的所有字符都是数字,则isdigit()方法将返回true。

然后可以这样读取正确的ID:

PROMPT = "Please enter your ID: "
user_id = raw_input(PROMPT)
while not id_valid(user_id):
    print "Sorry, that was an invalid ID. Please try again."
    user_id = raw_input(PROMPT)

“很抱歉,找不到书ID或书不可用。” 该消息被显示了很多次,因为您在ID不匹配或书籍不可用的每次迭代中打印该消息。 您可以使用布尔值标记来记住是否找到了这本书,并在最后打印该消息一次:

book_found = False
with open("book_list.txt", "r") as txt:
    for line in txt:
        data = line.split();
        if book_id == data[0] and len(data) == 3:
            # modify the file here
            print "You have successfully taken out the book."
            book_found = True

if not book_found:
     print "Sorry, either the book ID was not found or the book is unavailable."

假设每一行中的数据条目都由空格分隔,则可以使用split来分隔ID。 它将返回一个列表,其中[0]元素是书籍ID,[3]是用户ID(如果存在)。 如果没有用户ID,则列表将仅包含3个元素。

至于更新文件,最简单的策略是在处理原始文件时保存修改后的副本,如果要在最后保存修改,则将其覆盖。

您的代码中有两个问题:

  1. 不要在while循环中但在循环之前打开文件(并适当地添加错误检查)

     while True: txt = open("book_list.txt", "r+") 
  2. 如果写入r+文件,则将txt.write写入的所有行附加到文件末尾。 不要覆盖它们! 这意味着签出一本书后,您将在该书签出文件的末尾有一个新行。 覆盖文件更加复杂! 基本上有两种解决方案,您可以读取整个文件,也可以将其保存在字典或其他文件中。 然后使用w重写整个文件。 或者,这有点丑陋,您需要在每本书后面精确地放置四个空格,然后使用txt.seek用用户数覆盖这些txt.seek

  3. 比较book_id == line[0]基本上意味着您检查line的第一个字符是否等于书号,这与检查行的第一个数字是否与您的书号相同是不同的book_id == int(line[0:line.index(" ")])

  4. 您得到的缩进错误很难检查,但是基本上您必须检查您是IDE还是texteditor,如果它正确处理了空格和制表符,或者您是否某种程度上不关心缩进。

首先从while循环中删除open语句,它会不必要地打开文件。

while True:
    try:
         user_id = int((raw_input("Please enter your ID: ")))
         if len(str(user_id)) != 4:
            print "Sorry, that was an invalid ID. Please try again."
            continue
         break
    except:
       print "Sorry, that was an invalid ID. Please try again."

book_id = (raw_input("Please enter the book ID no. you would like to take out: "))

其次with while处理文件时使用with语句while因此您不必跟踪关闭它。 另外,在"r+"模式下打开文件会使问题变得更加复杂,因为最终将要添加数据,您可以利用seektell但是这样做不会使事情变得容易,也可能会覆盖数据,因此我建议您使用一个临时文件

out_txt = open("temp.txt","w")
found = False
with open("book_list.txt", "r") as txt:
    for line in txt:
        if book_id == line[0] and line[-1] == " ":          # are you sure that every line that does not have an user_id associated to it is going to have a " "(space) at the end of it, if not think of some other condition to do this

            line =  line.strip() + " " + str(user_id) + "\n"
            print "You have successfully taken out the book."
            found = True
        out_txt.write(line)

out_txt.close()
if found:
    import os
    os.remove("book_list.txt")
    os.rename(out_txt.name, "book_list.txt")
else:
        print "Sorry, either the book ID was not found or the book is unavailable."

暂无
暂无

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

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