我有要求用户输入然后将其写入文件的功能。但是,当程序运行时,它不会出现在文本文件中。这意味着当我试图读取我的文本文件时它是空的。如果我关闭我的程序,所有的书面文本都会出现在文本文件中。我有主要功能,您可以在其中选择阅读、编写或编辑记事本。在你选择一些东西后,主要功能调用其他功能。我不确定在这种情况下使用这种结构是正确的还是整体上不好。希望这是有道理的。def new_note(): file = open('notepad.dat', 'a') file.writelines('\n' + input("Write something: ")) file.writelines(":::" + time.strftime("%X %x")) file.close main()def read_file(): file = open('notepad.dat', 'r') notes = [(line.strip()).split() for line in file] print(notes) file.close main()
2 回答

红颜莎娜
TA贡献1842条经验 获得超12个赞
试试这个,它更pythonic:
def new_note():
with open('notepad.dat', 'a') as file:
file.writelines('\n' + input("Write something: "))
file.writelines(":::" + time.strftime("%X %x"))
main()
def read_file():
with open('notepad.dat', 'r') as file:
notes = [(line.strip()).split() for line in file]
print(notes)
main()
但是,如果您共享该功能,将会很有帮助main。从我在本地系统上的尝试来看,在省略调用时,上面的内容似乎没有引起任何问题main()。

泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
这里的问题是您无法在尝试同时写入文件时读取文件。此外,一旦 file.close 被调用,文件将被更新。发布数据将出现。您可以尝试重构您的程序。
添加回答
举报
0/150
提交
取消