【发布时间】:2020-11-24 16:42:11
【问题描述】:
节目说明:
程序从第一个输入中创建一个具有给定名称的
.txt文件。之后,它从每个输入中接受文件的文本行,直到输入仅包含字符串"end"(不应包括此结束行)。该程序还应该处理所有可能的错误。
我的解决方案:
def writef(f, st):
try:
assert st == "end", "* End of the file (not included)"
assert not(f.endswith(".txt")), "txt only"
except IOError:
print("Unexpected error")
except AssertionError as sterr:
print(sterr)
f.write(st + "\n")
t = input("* Beggining of the file (.txt supported only): ")
f = open(t, "w+")
while True:
exec_st = input("> ")
writef(f, exec_st)
问题:
- 我的程序接受各种文件。我不知道如何处理一个错误,该错误将显示文件应该是
.txt扩展名(正确显示 AssertionError 消息)。 - 如果字符串仅包含
"end":* End of the file (not included),则在每个输入行之后它还会输出AssertionError消息。但是,当我尝试输入仅包含单词"end"的字符串时,它会输出以下错误而不是 AssertionError:
Traceback (most recent call last):
File "C:\Users\1\Desktop\IT\pycharm\em_1.py", line 15, in <module>
writef(f, exec_st)
File "C:\Users\1\Desktop\IT\pycharm\em_1.py", line 4, in writef
assert not(f.endswith(".txt")), "txt only"
AttributeError: '_io.TextIOWrapper' object has no attribute 'endswith'
如果有任何帮助,我将不胜感激,在此先感谢。
【问题讨论】:
-
您在问两个不同的问题。也就是说,您还没有包含您的
writef()函数。 -
@ewong ,抱歉,确实错误地放置了我的解决方案的早期版本,进行了一些编辑
标签: python