Python Tutorial – Python File I/O

In this Python 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 Python Tutorial 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:

 

 

You can use it like this

 

 

 

This will be the result, make sure that you have file.txt in your working director.

Python Tutorial - Python File I/O
Python Tutorial – Python File I/O

 

 

 

 

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.

 

 

 

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×