简体   繁体   中英

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:

#!/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). i dont see any change in the txt file and no error is shown by the interpreter, its very strange, any help ?

first of all, always use the with statement variant, that will always close the file, even on errors:

#!/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. If you want to append, use '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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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