File Management in Python
Python programming language supports file management using File object which provides different methods to perform operations like open, read, write and append text into the files.
In this article, we will see the following methods and try to understand the file management concept in detail
Open()
This method is used to open the file. This method accepts two parameters, i.e., path or address of the file and access mode (read, write or append) open (file_address, access_mode). Access mode can be any of the following,
- r: open a file with the read access mode
- r+: open a file with the read and write access mode
- w: open a file with write access mode
- w+: open a file with write and read access mode
- a: open a file with append access mode
- a+: open a file with append and read access mode
Please note that ‘access_mode’ is an optional parameter and, by default, it is set to ‘read’. Let’s have a look at the example given below wherein you open a file that contains two lines of data and iterate through each line and print as an output to the console window.
- with open("c:\welcome.txt") as file: # Use file to refer to the file object
- for data in file: # this statement reads each line but one at a time
- print(data)

Open method raises an error ‘FileNotFoundError’ if the given file does not exist, as shown in the below example.
- try:
- with open("c:\welcomeNotExists.txt") as file: # Use file to refer to the file object
- #data = file.read()
- for data in file:
- print(data)
- except FileNotFoundError as fileNotFoundError:
- print(fileNotFoundError)

read([size])
This method is used to read and return the file data as a string. This method accepts one parameter (optional) i.e., size (characters) of the data to be read. Let’s have a look at the example given below
Example 1
Open a file and read the entire data, i.e., two lines of data and print to the console window.
- with open("c:\\welcome.txt") as file:
- data = file.read()
- print(data)

Example 2
Open a file and read first six characters data and print to the console window.
- with open("c:\\welcome.txt") as file:
- data = file.read(6)
- print(data)

readline[size]
This method is used to read the first line and return as a string. This method accepts one parameter (optional), i.e., size (characters) of the data to be read. Let’s have a look at the example given below
Example 1
Open a file and read the first line whereas file contains two lines of data
- with open("c:\\welcome.txt") as file:
- data = file.readline()
- print(data)
Example 2
Open a file and read the first six characters of the first line whereas file contains two lines of data
- with open("c:\\welcome.txt") as file:
- data = file.readline(6)
- print(data)






Join the conversation! Your thoughts help the community grow.