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?

Answers


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


Need Your Help

expect, assign output to buffer

buffer expect

#!/usr/local/bin/expect --

Executing powershell threads in IIS as impersonated user

c# asp.net powershell iis impersonation

I've been working on a web application that makes use of Powershell scripts. For some reason, even with ASP.NET impersonation, I am getting "access denied" errors on commands that require elevated ...