无法使用python将数据写入文件 [英] Unable to write data into a file using python

查看:61
本文介绍了无法使用python将数据写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.flush()
os.fsync(outfile)
outfile.close

这是代码段.我正在尝试将某些内容写入python文件中.但是当我们打开文件时,没有任何内容写入其中.我做错什么了吗?

This is the code snippet. I am trying to write something into a file in python. but when we open the file, nothing is written into it. Am i doing anything wrong?

推荐答案

您没有调用 outfile.close 方法.

无需在此处刷新,只需正确调用close:

No need to flush here, just call close properly:

outfile = open(inputfile, 'w')
outfile.write(argument)
outfile.close()

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

or better still, use the file object as a context manager:

with open(inputfile, 'w') as outfile:
    outfile.write(argument)

所有这些都假定 argument 不是一个空字符串,并且您正在查看正确的文件.如果您在 inputfile 中使用相对路径,则使用的绝对路径取决于您当前的工作目录,并且您可能正在查看错误的文件以查看是否已将某些内容写入其中.

This is all presuming that argument is not an empty string, and that you are looking at the right file. If you are using a relative path in inputfile what absolute path is used depends on your current working directory and you could be looking at the wrong file to see if something has been written to it.

这篇关于无法使用python将数据写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆