- What is a file?
- What is file encoding, like ASCII or utf-8, etc?
- What is File Access Mode? List of all file access modes in file handling operation.
- Which library is required to perform file handling or file input-output action?
- How to perform file handling operations in python?
- Tips of file handling in python.
- List of file handling functions in python.
- Examples of file handling operations in python.
1. What is a file?
A file is a named object on a system (computers/mobiles/servers) that contains data within it. This data can be a text file, audio or video stream, application, executable file, etc.
2. What is file encoding, like ASCII or utf-8, etc?
File encoding is the way to store the character set used in the file in the computer system. In python, input output operation is used the encoding standard to read or write the files. Based on the characters used you can use the below file encoding
- US-ASCII
When we use the characters only from US-ASCII. It stores a single character in of 7 bits. - UTF-8
For character set of EBCDIC and GB18030. It stores a single character in 8 bits. - UTF-16
This encoding is useful when we want to use all English characters & Asian characters. Each character is encoded in 2 bytes, ie. It stores a single character in 16 bits. - UTF-32
It is not used very frequently. It takes lots of memory. Each character is encoded in 4 bytes, ie. It stores a single character in 32 bits.
2.1 Example: Encoding a character ‘A’ with a different encoding standard.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 9 09:09:05 2021 website : http://mycloudplace.com @author: mycloudplace """ if __name__ == "__main__": input_str = "A" print("'A' encoded in ascii as : ",input_str.encode('ascii')) print("'A' encoded in utf-8 as : ",input_str.encode('utf-8')) print("'A' encoded in utf-16 as : ",input_str.encode('utf-16')) print("'A' encoded in utf-32 as : ",input_str.encode('utf-32'))
OUTPUT:
'A' encoded in ascii as : b'A' 'A' encoded in utf-8 as : b'A' 'A' encoded in utf-16 as : b'\xff\xfeA\x00' 'A' encoded in utf-32 as : b'\xff\xfe\x00\x00A\x00\x00\x00'
For more about encoding please click here. The same encoding is used while reading or writing the file in python.
3. What is File Access Mode? List of all file access modes in file handling python.
File access mode is used to perform all input output operations in python like reading, write or append. Below are the file access modes used in file handling operation in python.
S.No. | Access mode | Description |
1 | r | It opens the file to read-only mode. |
2 | rb | It opens the file to read-only in binary format. |
3 | r+ | It opens the file to read and write both. |
4 | rb+ | It opens the file to read and write both in binary format. |
5 | w | It opens the file to write only. |
6 | wb | It opens the file to write only in binary format. |
7 | w+ | It opens the file to write and read both. |
8 | wb+ | It opens the file to write and read both in binary format. |
9 | a | It opens the file in the append mode. |
10 | ab | It opens the file in the append mode in binary format. |
11 | a+ | It opens a file to append and read both. |
12 | ab+ | It opens a file to append and read both in binary format. |
4. Which library is required to perform file handling or file input-output operations?
We generally use the IO module to perform file input output operations in python. We can also perform the basic actions with the standard library.
Syntax to import io module
import io
5. How to perform file handling operations in python?
File handling in python can be performed using the standard file handling library and methods. Below are the operations on file handling in python
- Open a file (new or existing)
- Read or write to the file
- Close the file
5.1 Open a file (new or existing)
This is the first step to work with file handling in python. You can open a file(new or existing) using the Open() method. The Open() method takes 2 arguments
- Filename with complete path
- File mode
Syntax to open a file in python
file_object = open(<file-name>, <access-mode>, <buffering>)
5.2 Read or Write to the file
After opening the file you can perform read or write operation, to perform read/write you can also use the ‘with’ statement.
Syntax of reading/writing to a file in python
file_obj= open(<file-name>, <access-mode>,<encoding>)
Syntax of reading/writing to a file in python using the ‘with’ statement
with open(<file-name>, <encoding>) as file_obj:
# write code goes here
5.3 Close the file
After performing all input output operations like read/write/append, we finally need to close the file. We close the file to release the resource. You can use the Close() method to close the file
Syntax of closing a file in python
file_obj.close()
5.4 Example: Performing basic file input output (writing/reading) operation in python.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 19 16:52:51 2021 website : http://mycloudplace.com @author: mycloudplace """ if __name__ == "__main__": file_name = "abc.txt" print("Opening the file",file_name,"in writing mode") file_obj = open(file_name, 'w', encoding='utf-8') file_obj.writelines("Hello, This is sample text.") #adding a line to file file_obj.close() #closing the file print("We have successfully created a file.") print("Below we are going to read the above created file") file_obj_read = open(file_name, 'r', encoding='utf-8') print(file_obj_read.read())
OUTPUT:
Opening the file abc.txt in writing mode We have successfully created a file. Below we are going to read the above created file Hello, This is sample text.
6. Tips of file handling in python.
- Try to use with clause wherever possible.
- Always use try..catch block to perform file operation.
- Use encoding wherever possible.
- Always use buffering when you don’t know the size of the file you are going to deal with.
- Before opening a file it is always better to check if the file is already closed. This can be checked using the closed attribute.
- If you are dealing with the encoding & decoding of string and if you are strict with it, then use errors argument while opening the file.
file_obj= open(<file-name>, <access-mode>,<encoding>, errors=“strict”) - Use the readlines() function to read the content of the file one by one.
- Use os.getcwd() to get current working directory.
7. List of file handling functions in python.
- open(): It Opens the file to perform file input output operation.
- close(): It closes an opened file. It does not affect if the file is already closed.
- flush(): It flushes the write buffer of the file stream.
- isatty(): It returns True if the file stream is interactive else False.
- readable(): It returns True if the file stream can be read from.
- read(n): It reads at most n characters from the file. It reads till the end of the file if it is negative or None.
- readline(n=-1): It reads and returns one line from the file. Reads in at most n bytes if specified.
- readlines(n=-1): It reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.
- seek(offset,from=SEEK_SET): It changes the file position to offset bytes, about from (start, current, end).
- seekable(): It returns True if the file stream supports random access.
- tell(): It returns the current file location.
- truncate(size=None): It resizes the file stream to size bytes. If the size is not specified, resizes to the current location.
- writable(): It returns True if the file stream can be written to.
- write(str): It writes the string str to the file and returns the number of characters written.
- writelines(lines): It writes a list of lines to the file.
- fileno(): It returns an integer number of the file.
8. Examples of file handling operations in python.
Writing a program in python to read the first 4 characters from the file. Also, read the first 5 lines from the file.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 19 16:52:51 2021 website : http://mycloudplace.com @author: mycloudplace """ if __name__ == "__main__": file_name = "abc.txt" with open(file_name,'w', encoding='utf-8') as file_obj: file_obj.write("First line." + "\n") file_obj.write("Second line." + "\n") file_obj.write("Third line." + "\n") file_obj.write("Fourth line." + "\n") file_obj.write("Fifth line." + "\n") file_obj.write("Sixth line." + "\n") file_obj.write("Seventh line." + "\n") file_obj.write("Eighth line." + "\n") file_obj.write("Ninth line." + "\n") file_obj.write("Tenth line." + "\n") print("The first 4 characters from the file") file_obj_read = open(file_name,'r', encoding='utf-8') print(file_obj_read.read(4)) print("Reading the first 5 lines from the file") file_obj_read.seek(0) #Moving the cursor at the beginning of the file number_of_lines=5 n=1 while n <= number_of_lines: print(file_obj_read.readline()) n+=1 file_obj_read.close()
OUTPUT:
The first 4 characters from the file Firs Reading the first 5 lines from the file First line. Second line. Third line. Fourth line. Fifth line.
Below is our previous articles on python
- Modules in python tactics that can boost your python programming skills
- Python array | numpy for python | How to create numpy or np array in python
- Python Lambda Function With Examples | How To Create A New Anonymous function
- Python Useful Built-in Functions With Examples | How to create a new function
- python iteration | while loop | for loop with examples
- Python Data Types With Examples
- Python – installation indentation variable comments
- Python Programming Introduction
Nice article.
Thank you Neha
Pingback: A to Z of Python exception handling | Python try catch with example - Mycloudplace
Pingback: Python reporting libraries | Python reporting tools to generate interactive and beautiful reports - Mycloudplace