到目前為止,這就是我所擁有的。我正在嘗試讓程式要求用戶輸入一本書的作者和一本書的 ISBN,然后如果檔案中有一行包含這兩個變數,它將洗掉該行完全地。
print()
print("Removing a Book")
print()
removebookAuthor=(input("Provide the author of the book you would like to remove>"))
removebookISBN=(input("Provide the ISBN of the book you would like to remove>"))
with open("books.txt","r ") as f:
new_f = f.readlines()
f.seek(2)
for line in new_f:
if "removebookAuthor" "removebookISBN" in line:
f.write(line)
f.truncate()
作為參考,文本檔案如下所示:
Python Crash Course - 2nd Edition;Matthes,Eric;978-1593279288;005.133/MAT;12;8;
Python for Dummies;Maruch,Stef;978-0471778646;005.133/MAR;5;0;
Beginning Programming with Python for Dummies;Mueller,John Paul;978-1119457893;005.133/MUE;7;5;
Beginning COBOL for Programmers;Coughlan,Michael;978-1430262534;005.133/COU;1;0;
removebookAuthor 的示例為“ Maruch,Stef ” removebookISBN 的示例為“ 978-0471778646 ”
至此,程式徹底清除了整個檔案。不太清楚如何解決這個問題。幫助將不勝感激!
uj5u.com熱心網友回復:
您的 if 條件未正確寫入。您可以同時使用not in這兩種情況:
removebookAuthor = input("Provide the author of the book you would like to remove>")
removebookISBN = input("Provide the ISBN of the book you would like to remove>")
with open("books.txt", "r ") as f:
lines = f.readlines()
f.seek(2)
for line in lines:
if removebookAuthor not in line and removebookISBN not in line:
f.write(line)
f.truncate()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530143.html
