无法使用python将数据写入文件

A R*_*A R 1 python linux file

outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.flush()
os.fsync(outfile)
outfile.close
Run Code Online (Sandbox Code Playgroud)

这是代码段.我想在python中写一些文件.但是当我们打开文件时,没有任何内容写入其中.我做错了吗?

Mar*_*ers 5

你没有调用这个outfile.close方法.

无需在此处刷新,只需正确关闭:

outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.close()
Run Code Online (Sandbox Code Playgroud)

或者更好的是,使用文件对象作为上下文管理器:

with open(inputfile, 'w') as outfile:
    outfile.write(argument)
Run Code Online (Sandbox Code Playgroud)

这都假设argument不是空字符串,而是您正在查看正确的文件.如果您在使用inputfile绝对路径时使用相对路径取决于您当前的工作目录,您可能会查看错误的文件以查看是否已写入某些内容.