Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 写入文件失败?_Python_Python 3.x - Fatal编程技术网

Python 写入文件失败?

Python 写入文件失败?,python,python-3.x,Python,Python 3.x,我试图写入二进制(*.bin)文件,但遇到了一个问题。 当我使用以下代码时,它不会向文件写入任何内容: abc = str.encode("sabd") f=open("sbd.bin",'wb') f.write(abc) f.close 但是,当我使用以下代码时,它运行良好: abc = str.encode("sabd") with open("sbd.bin",'wb') as f: f.write(abc) 我使用Win+Python3。而不是f.close,尝试f.clo

我试图写入二进制(*.bin)文件,但遇到了一个问题。 当我使用以下代码时,它不会向文件写入任何内容:

abc = str.encode("sabd")
f=open("sbd.bin",'wb')
f.write(abc)
f.close
但是,当我使用以下代码时,它运行良好:

abc = str.encode("sabd")
with open("sbd.bin",'wb') as f:
    f.write(abc)

我使用Win+Python3。

而不是
f.close
,尝试
f.close()
看看是否效果更好,因为
close()
是一种方法。

我建议将数据刷新到文件中,而不是
f.close
,尝试
f.close()
看看效果是否更好,因为您缺少此选项,并且会导致文件无法创建或写入。e、 g.
file.flush()
将创建不存在的文件,并将数据写入其中


来源:根据cdlane的建议,在调用未获取变量或其他内容的方法时,请使用
file.close()
关闭该文件。

我建议将数据刷新到该文件,因为您缺少该文件,并且会导致无法创建或写入该文件。e、 g.
file.flush()
将创建不存在的文件,并将数据写入其中


来源:根据cdlane的建议,在调用一个没有获取变量的方法时,使用
file.close()
关闭该文件。

worket for me on linux,尝试传递
write
bytearray,也许这样就可以了。您需要调用
f.close
。所以使用
f.close()
。更好的方法是,使用
with
语句…在linux上为我工作,尝试传递
write
一个bytearray,也许这样就可以了。您需要调用
f.close
。所以使用
f.close()
。更好的是,使用
with
语句…正如您提供的链接所述,“Python在关闭文件时自动刷新文件”,因此在这种情况下您不需要自己调用它。是的,忘记了声明
文件.close()
调用
文件.flush()
,因为您提供的链接所述,“Python在关闭文件时自动刷新文件”,因此在这种情况下您不需要自己调用它。是的,忘记声明
file.close()
调用
file.flush()