Python 文件未关闭

Python 文件未关闭,python,Python,windows 7、python 2.7.2 以下运行不带错误: from subprocess import call f = open("file1","w") f.writelines("sigh") f.flush f.close call("copy file1 + file2 file3", shell=True) 但是,file3只包含file2的内容。file1和file2名称都会像windows中的正常情况一样进行回显,但调用副本时,file1似乎为空。似乎file1还没有

windows 7、python 2.7.2

以下运行不带错误:

from subprocess import call

f = open("file1","w")
f.writelines("sigh")
f.flush
f.close
call("copy file1 + file2 file3", shell=True)
但是,file3只包含file2的内容。file1和file2名称都会像windows中的正常情况一样进行回显,但调用副本时,file1似乎为空。似乎file1还没有完全写入和刷新。如果file1是单独创建的,而不是在同一个python文件中创建的,则会按预期运行以下操作:

from subprocess import call
call("copy file1 + file2 file3", shell=True)

很抱歉,这里要怪python新手。许多thx用于任何协助。

您缺少括号:

f.flush()
f.close()
您的代码在语法上是有效的,但不调用这两个函数

编写该序列的一种更具python风格的方法是:

with open("file1","w") as f:
    f.write("sigh\n") # don't use writelines() for one lonely string 
call("copy file1 + file2 file3", shell=True)

这将自动关闭
f
块末尾的
(并且
flush()
是多余的)。

缺少括号:

f.flush()
f.close()
您的代码在语法上是有效的,但不调用这两个函数

编写该序列的一种更具python风格的方法是:

with open("file1","w") as f:
    f.write("sigh\n") # don't use writelines() for one lonely string 
call("copy file1 + file2 file3", shell=True)
这将自动关闭
f
,在
块的末尾(并且
flush()
是冗余的)