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?
Asked
Active
Viewed 138 times
-6
-
4is there anything you have done so far? – Lafexlos Mar 12 '14 at 10:11
-
yes, I used like f=open(file1,'w+') that creates a file and i am nt able to make out whether it is opening the file if exists because the read()operation is ain't working since i opened in 'W' mode. and now if i write anything its overwriting the contents – rkatkam Mar 12 '14 at 10:16
-
1`file_object = open('my_file.txt', mode='a+')` – Trimax Mar 12 '14 at 10:17
-
wowww. Thanks Trimax, its working!! – rkatkam Mar 12 '14 at 10:21
-
possible duplicate of [How do you append to file in python?](http://stackoverflow.com/questions/4706499/how-do-you-append-to-file-in-python) – DNA Mar 12 '14 at 10:53
-
my question was how to create a file if doesnt exists and open the same file if it exists. – rkatkam Mar 12 '14 at 14:32
2 Answers
1
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

abrunet
- 1,122
- 17
- 31
0
You can use:
file = open('myfile.dat', 'a+')
Refer to this link for details: http://docs.python.org/2/tutorial/inputoutput.html

Shah
- 661
- 2
- 9
- 19