We have learned how to create and use variables in Python. However, this is a temporary arrangement; they cease to exist once the program finishes executing. Python provides the capability to store data permanently, allowing it to be used even after the program has terminated. This is known as 'file handling'.
For example: Storing Records, Read file data, Store notes etc.
What is File Handling in Python?
"File Handling" is a concept used to read, write and modify file in Python language. With this, we can:
- Create a File
- Read a File
- Write data to a File
- Update a File
File Mode
| Mode | Meaning | Behavior |
|---|---|---|
"r" | Read | Open a file only for reading. File must exist. |
"w" | Write | Open a file for writing. Creates a new file or overwrites an existing file. |
"a" | Append | Open a file to add data at the end. Existing content is preserved. |
"x" | Exclusive creation | Create a new file. Fails if the file already exists. |
"rb" | Read Binary | Read a file in binary mode (images, videos). |
"wb" | Write Binary | Write a file in binary mode. |
"r+" | Read & Write | Open a file for reading and writing. File must exist. |
"w+" | Write & Read | Open a file for reading and writing. Overwrites existing file. |
"a+" | Append & Read | Open a file for reading and appending. Adds new content at the end. |
Creating a New File
file = open("newfile.text", "x")
file.close()Opening a File
file = open("Python.text", "r") // Python.txt - file name, r - read mode
print(file.read())
Read a File
file = open("Python.text", "r")
print(file.read())
file.close()file = open("Python.text", "r")
print(file.readline())
file.close()file = open("Python.text", "r")
print(file.readlines())
file.close()Writing a File
file = open("note.txt", "w")
file.write("Python Programming")
file.close()Appeding Data
file = open("note.text", "a")
file.write("\nLearn from Scratch")
file.closeClosing File
Always close files after using them.
file.close()with open("note.text", "r") as file:
print(file.read())Save User Input
name = input("Enter your name: ")
with open("note.text", "w")
file.write("name +\n")
No comments:
Post a Comment