Create or open file in python
In python, I want to open a file if already exists or create it if it doesnt exist. also i want to write to the file new contents on opening it without overwriting the existing contents of the file. How can I do it?
PEP8 suggests you to use:
with open('test.txt', 'a+') as f: f.write( "Your new content" )
The with statement is better because it will ensure you always close the file, even if an exception is raised.
Example adapted from: http://docs.python-guide.org/en/latest/writing/style/#pep-8
You can use:
file = open('myfile.dat', 'a+')
Refer to this link for details: http://docs.python.org/2/tutorial/inputoutput.html