Python File Handling - Full Detailed Explanation with Examples
1. Opening Files in Different Modes
-------------------------------------
open("filename", "mode")
Modes:
- "r" : Read
- "w" : Write (overwrites)
- "a" : Append
- "b" : Binary mode
- "x" : Create new file
- "r+" : Read and Write
Example:
file = open("[Link]", "r")
file = open("[Link]", "w")
file = open("[Link]", "a")
file = open("[Link]", "rb")
file = open("[Link]", "x")
2. Accessing File Contents Using Standard Functions
------------------------------------------------------
- read() -> reads entire content
- readline() -> reads one line
- readlines() -> reads all lines into list
Example:
file = open("[Link]", "r")
print([Link]())
[Link]()
3. Reading and Writing Files
-------------------------------
Writing:
file = open("[Link]", "w")
[Link]("Hello World\n")
[Link]()
Appending:
file = open("[Link]", "a")
[Link]("\nAdding a new line")
[Link]()
4. Closing a File
------------------
Always close using [Link]()
Using with:
with open("[Link]", "r") as file:
print([Link]())
5. Renaming and Deleting Files
-------------------------------
import os
Renaming:
[Link]("[Link]", "new_sample.txt")
Deleting:
if [Link]("new_sample.txt"):
[Link]("new_sample.txt")
else:
print("The file does not exist.")
6. File Related Standard Functions
------------------------------------
| Function | Example |
|--------------------|----------------------------------|
| open() | open("[Link]", "r") |
| read() | [Link]() |
| readline() | [Link]() |
| readlines() | [Link]() |
| write() | [Link]("text") |
| writelines() | [Link](["line1\n"]) |
| close() | [Link]() |
| [Link]() | [Link]("[Link]", "[Link]") |
| [Link]() | [Link]("[Link]") |
| [Link]() | [Link]("[Link]") |