没有抛出错误,python创建了一个空白文件,不知道如何进行故障排除



我可以使用read命令和文件内容,但在写入文件时遇到问题。

我试过"w"one_answers"a",结果都一样。它总是创建目标文件,但它是空的(零字节(。

FILE_TARGET = ("DataAlbumUpdates.txt")
z=open(FILE_TARGET,"a")
z.write("Hello")
z.write("goodybye")
z.write("one")
z.write("two")
z.write("three")
z.flush
z.close

任何帮助都将不胜感激。。。有没有办法从write命令中获取返回代码?

读取/写入文件的Python方法是使用with语句。尽管您可以像您的示例中那样显式地调用open和close。不需要冲洗。

https://docs.python.org/3/tutorial/inputoutput.html

这将自动为您关闭文件。

您应该使用os.path来创建文件/目录的路径,这样可以避免任何错误。

您可以将写操作分配给一个变量,它将返回所写内容的字符数。

例如,如果您首先分配单词或在列表上迭代,则可以根据单词的长度来检查这一点。

import os.path
FILE_TARGET = os.path.join("Data", "AlbumUpdates.txt") # safely create the path.
# Use the with context to automatically close the file gracefully
with open(FILE_TARGET,"a") as z:
words = ["Hello", "Goodbye", "One", "Two", "Three"] # alist to iterate over, it will assign each word to a variable so you can check its length.
for w in words:
r = z.write(w) # assign the write to a variable.  It will return the length it wrote.
print(r == len(w)) # Check that what has written matches what was passed.

最新更新