Python File handling a method to store the output of the program to a file or take input from the file. File handling is a key concept in the programming world. File handling used in almost every kind of project. For example, you are creating an Inventory management system.
Using Python file handling you can store that data into the file. If you are trying to perform some analysis on the data then you must be provided with data in the form comma separated file or Microsoft Excel file. Using file handling you can read data from that file and also store output back into that file.
Python file handling operations also known as Python I/O deal with two types of files. They are:
- Text files
- Binary files
Even though the two file types may look the same on the surface, they encode data differently.
A text file is structured as a sequence of lines. And, each line of the text file consists of a sequence of characters. Termination of each line in a text file is denoted with the end of line (EOL). There are a few special characters that are used as EOL, but comma {,} and newlines are the most common ones.
Image files such as .jpg, .png, .gif, etc., and documents such as .doc, .xls, .pdf, etc., all of them constitute binary files.
Opening a File
To open a file, the built-in Python Function open() is used. It returns an object of the file which is used along with other functions.
Syntax of the Python open function:
obj=open(file_name , access_mode, buffer)
Here,
- The file_name refers to the file which we want to open.
- The access_mode specifies the mode in which the file has to be opened. It can be ‘r’, which is used for opening a file only to read it in Python, or ‘w’ used for opening a file only to write into it. Similarly, ‘a’ opens a file in Python in order to append, and so on. For more access modes, refer to the table given below.
- The buffer represents whether buffering is performed or not. If the buffer value is 0, then no buffering is performed, and when the buffer value is 1, then line buffering is performed while accessing the file.
Some of the most common access modes are listed below:
Modes | Description |
r | Opens a file only for reading |
rb | Opens a file only for reading but in a binary format |
w | Opens a file only for writing; overwrites the file if the file exists |
wb | Opens a file only for writing but in a binary format |
a | Opens a file for appending. It does not overwrite the file, just adds the data in the file, and if file is not created, then it creates a new file |
ab | Opens a file for appending in a binary format |
Here’s an example of Python open function and Python readlines for reading files line by line. Say, this is how our text file, ‘demofile.txt’ looks like:
This is just a text file But this is a newline
Now here’s a code snippet to open the file using file handing in Python.
f= open(‘demofile.txt’, ‘r’) f.readline()
With the help of the open function of Python read text file, save it in a file object and read lines with the help of the readlines function. Remember that f.readline() reads a single line from the file object. Also, this function leaves a newline character (\n) at the end of the string.
Output:
‘This is just a text file,\n’
Go for this in-depth job-oriented Python Training in Hyderabad now!
Writing into a File
The write() method is used to write a string into a file.
Syntax of the Python write function:
File_object.write(“string”)
Example:
i=open(“demotext.txt”,”w”) i.write(“Hello Intellipaat”)
Here, we are opening the demotext.txt file into a file object called ‘i’. Now, we can use the write function in order to write something into the file.
Reading from a File
The read() method is used to read data from a file.
Syntax of the Python read function:
File_object.read(data)
Example:
j=open(“intellipaat.txt”,”r”) k=j.read() print(k)
Output:
Hello Intellipaat
Closing a File
The close() function is used to close a file.
Syntax of the Python close function:
File_object.close()
Example:
j=open(“intellipaat.txt”,”r”) k=j.read() print(k) j.close()
Output:
Hello Intellipaat
We have the perfect professional Python Course in Bangalore for you!
Methods of File Handling in Python
There are different file handling in Python which are as follows:
- rename(): This is used to rename a file.
import os os.rename(existing file_name, new file_name)
- remove(): This method is used to delete a file in Python.
import os os.remove(“abc.txt”)
- chdir(): This method is used to change the current directory.
import os os.chdir(“new directory path”)
- mkdir(): This method is used to create a new directory.
import os os.mkdir(“new directory path “)
- rmdir(): This method is used to remove a directory.
import os os.rmdir(“new directory path”)
- getcwd(): This method is used to show the current working directory.
import os print(os.getcwd())
Other Methods of File Handling in Python
Following are the other common methods of file handling in Python, along with their descriptions
Method | Description |
close() | To close an open file. It has no effect if the file is already closed |
flush() | To flush the write buffer of the file stream |
read(n) | To read at most n characters from a file. Remember that it reads till end of file if it is negative or none |
readline(n=-1) | To read and return one line from a file. Remember that it reads at most n bytes, if specified |
readlines(n=-1) | To read and return a list of lines from a file. Remember that it reads at most n bytes/characters if specified |
seek(offset,from=SEEK_SET) | It changes the file position to offset bytes, in reference to (start, current, or end) |
tell() | It returns the current file location |
writable() | It returns true if the file stream can be written to |
write(s) | To write string s into a file and return the number of characters written |
writelines(lines) | To write a list of lines into a file |
Comments
Post a Comment