简体   繁体   English

使用Python 2.7.3 File.write()函数时缺少文件

[英]Missing file when using Python 2.7.3 File.write() function

If you are simply planning to write to a file using a python script as show below: 如果您只是打算使用python脚本写入文件,如下所示:

#!/usr/bin/python
count = 1
fo = open('DbCount.txt', 'w')
fo.write(str(count))
#fo.flush()
fo.close()

The Dbcount.txt file which was placed in the same folder as the script(attempting to modify the Dbcount.txt). Dbcount.txt文件与脚本位于同一文件夹(试图修改Dbcount.txt)。 i dont see any change in the txt file and no error is shown by the interpreter, its very strange, any help ? 我没有看到txt文件中的任何更改,并且解释器未显示任何错误,这很奇怪,有帮助吗?

first of all, always use the with statement variant, that will always close the file, even on errors: 首先,始终使用with语句变体,即使出现错误也总是关闭文件:

#!/usr/bin/python
count = 1
with open('DbCount.txt', 'w') as fo:
    fo.write(str(count))

then the 'w' overwrites your file each time you write to it. 那么'w'在您每次写入文件时覆盖您的文件。 If you want to append, use 'a' . 如果要追加,请使用'a'

About your specific problem, did you look only in the directory of your script, or in the current directory you're calling the script from? 关于您的特定问题,您只查看脚本的目录还是您从中调用脚本的当前目录? As you wrote your code, the file's path you write to is relative to where you execute your code from. 在编写代码时,要写入的文件路径是相对于执行代码的位置。

try: 尝试:

import os
count = 1
with open(os.path.join(os.path.dirname(__file__), 'DbCount.txt'), 'w') as fo:
    fo.write(str(count))

then it should output DbCount.txt in the same path as your script. 那么它应该在与脚本相同的路径中输出DbCount.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM