DEV Community

Cover image for How To Write A File Python Tutorial
Kelly Richardson
Kelly Richardson

Posted on

How To Write A File Python Tutorial

How To Write A File Python Tutorial

When it comes to Python programming, one of the basic things you can do is to either write or read a file. Although the process isn't complicated, you may need a helping hand if you're a beginner.

Whether you're an essay writer who wants to learn a little bit of coding or a tech enthusiast, this tutorial will come in handy.
In this guide, you will learn everything you need to know about files and how to write them. What does a file contain? Why is it so important in Python? Let's find out, shall we?

What Is a File?

Just before we hop right into the basics of writing a file, it's important to outline what a file is and how it works.
In very simple terms, a file is a set or sequence of bytes that is used to store data of any kind. Usually, this data is perfectly organized in varying formats.
A Python file typically contains three main parts: the header, data, and the End of File (EoF).
The header contains all the details about the file's content. From the file name to its size and format, the basic file details can be found in the header.
The data is the main meat of the file. It is the content of the file which you have created.
On the other hand, the End of File indicates the end of the file, just like the name implies. It typically comes in the form of a special character or code.

File Paths

In very simple terms, a file path tells you everything you need to know about the location of a file. It is typically made up of three different parts which include:
The folder path: This is the location of the folder in which the file is contained. You can have several folders containing different files. Ever had to write an essay in high school before? Remember how you had to save all materials and files in a folder titled "write my essay"? That's exactly how folder paths work.
The file name: This is what the file is named or titled. For instance, you could have a file named " dogs.gif" within a specific folder.
File extension: The file extension indicates the type of file in question. It is represented with a period and comes at the end of the file path. For instance, in the file "dogs.gif", the file extension is ".gif" which conforms to the Graphics Interchange Format (GIF) specification.

How Can You Open or Close Files in Python?

Before writing or handling any file in Python, you'd need to learn how to open it. However, there's no need to panic. Opening a file is as easy as snatching candy from a baby who doesn't want it.
All you need to do is use the open() built-in function which is represented by open( ).
For instance, if you're trying to open a text file titled "cat colors", you could invoke the open function like this:

file = open ( 'cat_colors.txt')

Easy Peasy!

However, one mistake most beginner programmers make is forgetting to close a file after opening it. Once you have opened a file, you have to ensure that you close it properly.
In some cases, a file may close on its own when you terminate an application or script. However, this isn't guaranteed and no professional programmer counts on it.
One of the most popular ways to close any file is by using the with statement.

For instance:
with open ( 'cat_colours.txt') as reader:

When invoked, the with statement automatically ensures that the file is closed once it is out of the with block. Even in cases of unexpected errors, you can still rest assured that your file will be closed when all is said and done.
If you're a beginner who is still trying to get a hang of closing a file, the with statement will come in handy. Not only does it help you create cleaner code, but it also makes it easier to handle any unexpected errors.

How to Write a File

Now that we've covered the basics of opening and closing a file, it's time to get to the crux: writing files. There are several methods anyone can use when dealing with python write to file. Here are two popular ones:
The write() file method
The write method writes any specified text to the file. This is used to write to a file that already exists. The position of the stream and the file mode will determine where you should insert the specified text:

"W": This deletes any text or content already existing and creates a new one. Empty the file first before putting the string at the current file stream position, the default value is 0.
For instance:
f = open("ipsumloremsample1.txt", "w")
f.write("Under new management!")
f.close()

"a": This is for adding text (appending) and the default placement at the end of the file. Here, you should place the text at the current file stream position. Open the file and use "a" to append content. Add text to the file and then close.
For instance:
f = open("ipsumloremsample2", "a")
f.write("Welcome to my world!")
f.close()

To read the file after appending or overwriting, use the open() function like this:
f = open("ipsumloremsample.txt", "r")
print(f.read())
writelines(sequence)

This method writes all specified lines at once. The (sequence) refers to the order in which the strings appear. You may be required to add the necessary line endings yourself as there are none added to each sequence item.
Follow this rule when using the writelines(sequence) method:
fileObject.writelines( sequence )

For instance, the specified text you want to write could be in a list “Ipsumloremsamplelist”. In this case, you should create a new file by creating the file object “outF” with “w” to indicate that you want to write the file.
outF = open("myOutFile.txt", "w")
outF.writelines(all_lines)
outF.close()

Now that you’ve learned how to open a Python read file and how to Python write a file, you're only a few steps away from becoming a pro Python programmer. Don't forget to keep scripting and practicing.
Good luck!

Top comments (0)