Python Tutorial : How to Write and Create Files

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")

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

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

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")

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

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

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!")

#reopen the file to see the newly added data 

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

Leave a Reply

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

You are commenting using your 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