Python Tutorial : How to Write and Create Files

ModesExplanation
xCreates new file ; Returns an error if the file exists
aAppends file ; Creates the file if it does not exist
rOpens files for reading or error if the file does not exist
wOpens and writes in file or creates the file if it does not exist

To create and write in a new Python file, a new file must be opened first. This is done by using open()

open has Two parameters : the file’s name and the Mode. The mode is how you interact with the file. The example below will Create a new file using the “x” mode

 #Here a new File is being created & some context is being written into the file

f = open("newFile.txt", "x")
 f.write("Putting content in the file")
 f.close()

Here the new file is being read and content will be displayed

f = open("newFile.txt", "r")
print(f.read())

A file’s content can be overwritten by using the “w” mode

 f = open("newFile.txt", "w")
 f.write("Content was overwritten, here is new data")
 f.close()

#here we reopen the file to check if context has changed 

f = open("newFile.txt", "r")
print(f.read())

Use “a” to append more context to a file without overwriting a file’s data

 f = open("newFile.txt", "a")
 f.write("New data was added!")
 f.close()

#reopen the file to see the newly added data 

f = open("newFile.txt", "r")
print(f.read())

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s