【发布时间】:2020-12-05 14:52:40
【问题描述】:
我一直在尝试创建一个程序,允许用户查看文本文件的内容并删除部分或全部单个条目块。
文本文件内容的示例如下所示:
Special Type A Sunflower
2016-10-12 18:10:40
Asteraceae
Ingredient in Sunflower Oil
Brought to North America by Europeans
Requires fertile and moist soil
Full sun
Pine Tree
2018-12-15 13:30:45
Pinaceae
Evergreen
Tall and long-lived
Temperate climate
Tropical Sealion
2019-01-20 12:10:05
Otariidae
Found in zoos
Likes fish
Likes balls
Likes zookeepers
Big Honey Badger
2015-06-06 10:10:25
Mustelidae
Eats anything
King of the desert
因此,入口块是指所有没有水平空格的行。
目前,我的进度是:
import time
import os
global o
global dataset
global database
from datetime import datetime
MyFilePath = os.getcwd()
ActualFile = "creatures.txt"
FinalFilePath = os.path.join(MyFilePath, ActualFile)
def get_dataset():
database = []
shown_info = []
with open(FinalFilePath, "r") as textfile:
sections = textfile.read().split("\n\n")
for section in sections:
lines = section.split("\n")
database.append({
"Name": lines[0],
"Date": lines[1],
"Information": lines[2:]
})
return database
def delete_creature():
dataset = get_dataset()
delete_question = str(input("Would you like to 1) delete a creature or 2) only some of its information from the dataset or 3) return to main page? Enter 1, 2 or 3: "))
if delete_question == "1":
delete_answer = str(input("Enter the name of the creature: "))
for line in textfile:
if delete_answer in line:
line.clear()
elif delete_question == "2":
delete_answer = str(input("Enter the relevant information of the creature: "))
for line in textfile:
if delete_answer in line:
line.clear()
elif delete_question == "3":
break
else:
raise ValueError
except ValueError:
print("\nPlease try again! Your entry is invalid!")
while True:
try:
option = str(input("\nGood day, This is a program to save and view creature details.\n" +
"1) View all creatures.\n" +
"2) Delete a creature.\n" +
"3) Close the program.\n" +
"Please select from the above options: "))
if option == "1":
view_all()
elif option == "2":
delete()
elif option == "3":
break
else:
print("\nPlease input one of the options 1, 2 or 3.")
except:
break
delete_function() 旨在通过以下方式删除生物:
- 名称,删除与名称关联的整个文本块
- Information,只删除一行信息
但是,我似乎无法让 delete_creature() 函数工作,而且我不确定如何让它工作。
有人知道如何让它工作吗?
非常感谢!
【问题讨论】:
-
我这样做的方法是逐行复制文件,如果您打算删除它,则不要添加它。不过可能有更好的方法。
-
@PatrickArtner:OP 已经有一个
get_dataset函数,可以将文件解析为 dict 列表。恐怕问题不在于(仅)从文件中删除一行 - 删除整个部分没有意义...... -
文件使用文件指针。您不能在不重新加载文件的情况下多次读取相同的行。 with() 之类的上下文处理程序也会关闭文件-因此您的代码会在您的删除函数内的
for line in textfile:上产生错误...这似乎根本不起作用...参见why-can-i-read-lines-from-file-only-one-time-本质上也是如此:您的删除函数“提示”删除和更新应该是不同的函数并且应该在解析的列表上工作 - 而不是文件 -
看起来好像有人写了一个框架(数据解析),没有人负责删除/更新的任务。这是部分给定代码的作业吗?
标签: python function user-input standard-library