Open a file in a function and write to it
I created the function below:
def print_form(x):
f = open('/home/rv/Plone/Zope-2.10.11-final-py2.4/Extensions/test.fasta', 'w')
f.write(str(x))
f.close()
return x开发者_C百科
The function returns and prints, but doesnt write it to a file or creates it?
EDIT
I editied the above code the so the file is created in a specific location but it still isnt there
The file 'form.fasta' will be created in the current working directory. This is usually whatever directory you're in when you invoke the script.
To see what your current directory is, add:
print(os.path.abspath(os.curdir))
or equivalent.
Also, make sure f.write(x)
converts x
to something fit to be written; you might want f.write(str(x))
or f.write(repr(x))
or even f.write(unicode(x))
.
Finally, just because you called f.close()
doesn't necessarily mean the OS has immediately flushed it out to the disk. (I can't seem to find a Python equivalent to C's setvbuf()
function, which would let you switch a file stream to unbuffered mode.)
P.S. One more thing: If x
is, say, an integer, just writing it to a file doesn't end the file with a line end character. If you have a one-line file without a line end, and you print it out, and you're like me and have a bash prompt string that starts with the line-clear control code, it will look exactly like the output you get from an empty file.
精彩评论