In this short tutorial, we learn how to use Python to create a file. We also look at the write, read, and append file handling methods.
This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.
Like most programming languages, Python too supports file handling. However, since Python treats files as text or binary, handling files is much easier. The most used file handling methods are to create, read and write files.
In this tutorial, we largely focus on how to use Python to create a file as this is the first step to file handling. However, we do introduce you to how you could read and write files.
To create a file in Python we use the in-built
open() function. There are other methods that utilize the OS module in Python, however, a few methods would require root permission. Hence to standardize this tutorial I have only used the
open(file, access mode)
open() methods require two parameters,
File- Required, the name or path of the file.
Access mode- Access modes govern the type of operations you would be performing.
Since we are trying to create a file, the access mode we would use is “x”. I’ve added a list of all the access modes below.
f = open("myfirstfile.txt", "x")
In the above code, we have used the
open() to create a file, since we have not specified a path, the file is created in the same directory as the script.
In case the file already exists, Python returns a
FileExistsError. Try running the same code twice and you will receive this error.
Apart from the create method, I’d like to give you an introduction about the read, write and append methods. I’ve added below a list of all the methods along with their access modes.
FileNotFoundErroris returned if the file does not exist.
As you may have noticed, the write and append methods can also be used to create files. However, I would recommend you familiarize yourself with the create methods first before you start to use other methods in Python to create files.
This is because the write method overwrites the existing data. Although the append methods do not overwrite data both these methods are not very user-friendly while creating files. Hence do practice creating files first before you start using the other methods to do the same.
Do let me know your thoughts in the comments section below. :)
Источник: dev.topython programming tutorial