Python File I/O

In this tutorial we want to learn about Python File I/O, so Python is popular programming language and it is used for different tasks, including file input/output (I/O). Python provides an easy way to read and write files, and it is the popular choice for tasks that has file processing, in this article we want to talk about the basics of Python file I/O and demonstrate how it can be used to perform common file operations.

 

 

Python Reading a File

For reading a file in Python, first of all we need to open it using open() function. open() function takes two parameters, the first one is name of the file that should be opened and the second one is the mode of the file,mode can be r for reading, w for writing, a for appending or a combination of these modes.

 

For example for opening a file named file.txt, we can use this code:

 

After that the file is open, we can read its contents using read() method, this will read the entire contents of file and store it in the contents variable.

 

 

 

We can also read a file line by line using readline() method:

 

 

After that we have finished reading a file, we need to close it using close() method:

 

 

Python Writing to a File

For writing to a file in Python, we also need to open it using open() function, but this time we use w mode like this:

 

 

after that the file is open, we can write to it using write() method:

 

 

Once we have finished writing to a file, we need to close it using close() method like this:

 

 

Python Appending to a File

For appending to a file in Python, we use a mode when opening the file:

 

 

After that the file is opened, we can append to it using write() method.

 

 

After we have finished appending to a file, we need to close it using close() method.

 

 

Learn More

Leave a Comment