In a python script, how can I save the contents of a string to file, and the file is in current directory? i.e the same directory as the test.py script file
views:
38answers:
2
A:
This will create/overwrite myfile.txt in the current working directory.
The Python 'current working directory' is inherited from the operating system. I.e., it's the directory you were 'in' when you ran the script. (Which isn't always the directory containing the script; e.g., scripts in distant directories can be executed by typing the full path.)
s = 'My string.'
with open('myfile.txt', 'w') as f:
f.write(s)
Jon-Eric
2010-07-30 02:00:37
+3
A:
If you want the path to the currently executing file (and not the working directory) use the
__file__
variable. You should note that this is the current file being run. So if you use it in an imported module, you'll get the path to the module, etc..
fH = file(os.path.join(os.path.dirname(__file__), 'someFile.txt'), 'w')
fH.write('here is my string')
fH.close()
Mark
2010-07-30 02:14:07