How would you feel after hours, probably days of hectic coding, and the unthinkable happened; you just found out that all your long hours of labor couldn’t be saved on your OS? Frustrating right? That’s why a programmer needs to understand everything about Python File Handling.
In the following paragraphs, you’ll be fully equipped with what is a Python file, the uses of a python file, and also the types of python files. You’ll also learn all the steps involved in python File Handling like “python create file”, python Read file, and python open file. Most importantly, you will be shown how to delete python files. Let’s begin.
Simply stated, a python file is an arranged storage that holds python programs that are managed by the OS. Though the python variables hold Programs temporarily in the process of coding. But it’ll be best that after the termination of the program, you should be able to come back to saved work. A computer file has two parts which are: filename and extension. A file is made of two Features that is: the filename and file path. Progressively, the filename is separated by a dot (.). So you know
The following are the 14 Files type that Python can handle:
- Comma-separated values (CSV)
- Plain Text (txt)
- Hierarchical Data Format
The python file is for storage, which works to avoid data loss. To an advantage, it also enables file sharing between users. The ability to manipulate these stored programs for a named purpose is known as file handling. Therefore, file handling in python is worth knowing.
Python File Handling is the ability for a user to navigate or manipulate the saved programs on the Os. The ability of a programmer to handle and manipulate python files is concluded into four categories which are:
- Python Open Files
- Python Read Files
- Python Write/create files
- Python Delete Files
Before you have access to other file features and manipulation, you have to first open the file. You open a file in python with the open ( ) function. However, you don’t just open a file in Python, you must indicate the purpose for opening the file. This process includes you stating the file name and opening mode like this: file_object = open(filename [, mode] [, buffering])
- File_name locates the storage that holds the file you want to open
- The mode determines how the file should open. After opening the file what should it do e.g read, or write
- Buffering simply means if python should be storing the opening process of the file or not. Which is decided by setting the buffering to 1 and 0 respectively.
Use the functions below to decide how your file should be opened
|r||This is a default mode that Opens a file for reading only.|
|RB||Opens a file for reading only in binary format_default mode.|
|r+||Opens a file for both reading and writing.|
|rb+||Opens a file for both reading and writing in binary format.|
|w||Opens a file for writing only(Overwrites the file if the file exists, creates a new file for writing)|
|wb||Opens a file for writing only in binary format(Overwrites the file if the file exists, creates a new file for writing)|
|w+||Opens a file for both writing and reading(Overwrites the existing file if the file exists, creates a new file for reading and writing)|
|wb+||Opens a file for both writing and reading in binary format(Overwrites the existing file if the file exists, creates a new file for reading and writing).|
|a||Opens a file in the append mode) it creates a new file for writing)|
|ab||Opens a file for appending in binary format( If the file does not exist, it creates a new file for writing)|
|a+||Opens a file for both appending and reading( file opens in the append mode, it creates a new file for reading and writing)|
|ab+||Opens a file for both appending and reading in binary form(file opens in the append mode, creates a new file for reading and writing)|
Example of opening python file with mode description
Once a file is open, you have access to all its attributes which are:
- file. closed: Gives logical feedback True if the file is closed and False if it isn’t
- file.mode: tells the user the mode in which the file was opened
- file.name: tells the user the name of the file he is working on
With the above vital information gathered, it’s time you understand python file handling properly.
After file opening, a user should be able to carry out the four basic file operations in Python which are: python write file, python Read file, python save the file, and python rename file and in completion: python Delete Files
Once a file has been opened in Python, you can create a file by writing_using the write( ) function.
Example of Python write() file function
with open("test.txt", 'we, encoding = 'utf-8') as f: f.write("my first file\n") f.write("This file\n\n") f.write("contains three lines\n")
What the above command will affect is
- Creates a new file for writing if there’s none
- If it already exists, it’ll Overwrite it
Another example of Python write a text.txt file with the output
# Write text data to a file with open('filename. txt', 'wt') as f: f.write ('hi there, I have some good news for you file.\n') f.write ('and another line.\n')
Hi there, I have some good news for you. and another line.
You can also open the python file for any of the reading purposes with the read( ) function. You can decide if you want to read only text data or read binary data. Anyways, make sure to specify the mode of python Read file you want to affect
Example of python read( ) file function
>>> f = open("test.txt", 're, encoding = 'utf-8') >>> f.read(4) # read the first 4 data 'This' >>> f.read(4) # read the next 4 data ' is ' >>> f.read() # read in the rest till the end of the file 'my first file\nThis file\contains three lines\n' >>> f.read() # further reading returns an empty string ''
The above is the text file ( text.txt) reading command.
Although python automatically closes after it has finished executing all the written codes. Interestingly, there is a provision for a user to close a python file at will. You can close a python file by using the close( ) function. The syntax for python file close is file_object.close()
#!/usr/bin/python # Open a file fo = open("foo.txt", "wb") print "Name of the file: ", fo. name # Close opened file fo. close()
Output: Name of the file: foo.txt
The above indicates that the file has been concluded, that’s a closed file.
It’s about time you know the truth. What if there’s a file that you must get rid of? The good news is that python makes that the easiest process and there’s no bad news. Positively, you should know how to command the python delete File.
You command the Python Delete File by using the remove ( ) function to delete files. To achieve this, you join the file name to the removed function, like this os. remove(file_name)
Example to delete Filename text7.txt
#!/usr/bin/python3 import os # Delete file test7.txt os. remove("text7.txt") The output will be a deleted "text7.txt" from the Os.
That’s enough knowledge of Python File Handling. However, there’s a bonus on how to rename a python file and how to save it.
The need to modify a python file is vital, and to rename a python file is easy, all you need to do is write the name of the new file next to the file name you wished to change from, demarcating it with a comma(,). Augment it to the rename function.
Rename syntax os. rename(current_file_name, new_file_name)
#!/usr/bin/python3 import os # Rename a file from test1.txt to test2.txt os. rename( "test1.txt", "test2.txt" )
Before you run your edited code on python, the file must be saved in the OS. You can save your file as a python file (.py) or as a text File (.txt). Preferably, always save your python codes as .py. The following are ways to save your python file on your OS
- After you’re done creating or editing. your code, click file on the upper. left of your python display interface
- Click on save file
- Edit and save with the name you can remember
That’s a whole lot of buns!
A computer file has two parts which are: filename and extension. A file is made of two Features that is: the filename and file path. Progressively, the filename is separated by a dot (.). Interestingly, python can handle 14 Files and more.
The python file is for storage to avoid data loss. Advantage, it also enables file sharing. The ability to manipulate these stored programs for a named purpose is known as file handling
Python File Handling is the ability of a user to navigate and manipulate saved programs in the OS
And Here, we bring the class to a close. Now you’re equipped with the need to start your python file handling Carrier, As always stated, you must put to practice all that you’ve read for maximum output. Good luck Coding!