In this article, we will discuss all about file handling in Python. Let us have a quick look at the contents shown below:
- Introduction
- File open
- Syntax
- Read files
- Parts of file to read
- Read lines
- loop
- Choose files
- Write files
- Append
- Splitting words
- Create a new file
- Seek method
- Rename file
- Remove files
- Directory method
Introduction
A file is a collection of data stored on a secondary storage device like a hard disk. Files are non-volatile storage media.
File open
The function to open a file in Python is open() function and it takes two parameters. One is filename and another is mode. The methods to open a file are:
- ” r “: Open a file for reading. But error occurs if the file doesn’t exist.
- “a “: Open a file for appending and create a file if it doesn’t exist.
- “w”: Open a file for writing and creates a file if doesn’t exist.
- ” x “: Creates a specified file. But returns error if not there.
- ” t”: It’s a default value for text mode.
- ” b”: it’s for binary mode.
Syntax
file= open("myfile.txt", "rb")
print(file) #file name and access modeare specified here
If the file doesn’t exist you will get an error.
Read files
In order to read the content of the files, we can use the read() method.
file=open("myfile.txt","r")
print(f.open())
Parts of a file to read
We also can read a part of a file we want to. The number of characters should be mentioned in this case.
file=open("myfile.txt","r")
print(f.open(5)) #returns Hello(the required word)
Read Lines
The method readline() returns a line in Python.
file=open("myfile.txt","r")
print(f.readline())
print(f.readline()) #two readline() methods are used for reading two lines
Loop
Loop through the lines can print the whole file.
file = open("myfile.txt", "r")
for x in file:
print(x)
Close files
This method closes the file object. Once a file object is closed you can;t further read from or write into the file object.
file= open("myfile.txt","wb")
print("Name of the file : ",file.name)
print("File is closed . ",file.closed)
print("File is now being closed... You cannot use the file object ")
file.close()
print("File is closed ",file.close())
print(file.read())
Output of the above code will generate an error.
Name of the file : myfile.txt
File is closed . False
File is now being closed... You cannot use the file object
File is closed . True
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\file.py",line 7, in <module>
print(file.read())
valueError: I/O operation on closed file
Write a file
Te write() method is used to write a string to an already opened file. This method does not add a newline character (‘\n’) to the end of the string.
file= open("myfile.txt", "w")
file.write("Python is interesting")
file.close()
print("Data written into the file") #returns Data written into the file
Append()
To append a file, one must open it using ‘a’ or ‘ab’ mode depending on whether it is a text file or a binary file.
file= open("myfile.txt", "a")
file.write("\n Python is interesting")
file.close()
print("Data appened to file.........") #returns Data appened to file.........
Splitting words
Python allows you to read lines from a file and splits the line based on a character. By default, this character is space but you can even specify any other character to split words in the string.
with open("myfile.txt", "r") as file:
line = myfile.readline()
words=line.split()
print(words)
Create a New File
To create a new file Python use open() method along with three modes of operations.
- “x”:Create
- “a”:Append
- “w”: Write
The above three modes will generate an error if no file exists.
seek() method
This method is used in case of a read or write at a specific position. This method takes two parameters. One is offset value and another is the from. The from parameter takes three kind of values. Those are:
- 0 for offset calculated from the beginning.
- 1 for offset calculated from the current position and
- 2 for offset calculated from the end.
The syntax: file.seek(offset, from)
We are assuming that the file myfile.txt contains “Python Tutorial” and the following is the code.
file=open("myfile.txt","r+")
file.seek(7,0)
lines=file.readlines()
for i in lines:
print(i)
file.close()
Rename file
The rename() method takes two arguments the current filename and new filename.
Syntax: os.rename(old_file_name, new_file_name)
See here we use the os module. This module in Python has various methods that can be used to perform file processing operations like renaming and deleting files. To know more you can refer to this site.
import os
os.rename("myfile.txt", "PythonTutorial.txt")
print("File Renamed")
Remove file
This method remove files. This method takes a filename as an argument and delete that file.
syntax: os.remove(file_name)
import os
os.remove("myfile.txt")
print("File Deleted") #returns File Deleted
Directory Methods
Python has various methods in the os module that help programmers to work with directories. This methods allow users to create, remove, and change directories.
mkdir() method is used to create a new directory in the current path.
import os
os.mkdir("New Dir")
print("Directory Created") #returns Directory Created
chdir() method is used to change the current directory.
import os
print("Current working directory is : ",os.getcwd()) #display current working directory
os.chdir("New")
print("The current directory is now....",end = ' ')
print(os.getcwd())
rmdir() method is used to remove or delete directory
import os
os.rmdir("New")
print("Directory Deleted........")#returns Directory deleted