Back to: Python
0
Python File Operations (Read, Write, Append, Delete)
Everything you need for handling files in Python.
## 1. Write to a File
Creates a file if it does not exist. Overwrites if it exists.
data = “Hello, this is a sample text file.”
with open(“sample.txt”, “w”) as file:
file.write(data)
This creates sample.txt with the content:
Hello, this is a sample text file.
## 2. Read a File
Read entire file:
with open(“sample.txt”, “r”) as file:
content = file.read()
print(content)
Read line-by-line:
with open(“sample.txt”, “r”) as file:
for line in file:
print(line.strip())
Read all lines in a list:
with open(“sample.txt”, “r”) as file:
lines = file.readlines()
print(lines)
## 3. Append to a File
Adds content at the end without erasing existing data.
with open(“sample.txt”, “a”) as file:
file.write(“\nThis line is appended.”)
## 4. Write Multiple Lines
lines = [“First line\n”, “Second line\n”, “Third line\n”]
with open(“sample.txt”, “w”) as file:
file.writelines(lines)
## 5. Read & Write JSON File
(Useful file format)
Write:
import json
data = {“name”: “Shanvi”, “age”: 25}
with open(“data.json”, “w”) as file:
json.dump(data, file, indent=2)
Read:
import json
with open(“data.json”, “r”) as file:
data = json.load(file)
print(data)
## 6. Check if File Exists
import os
if os.path.exists(“sample.txt”):
print(“File exists!”)
else:
print(“File not found!”)
## 7. Rename a File
import os
os.rename(“sample.txt”, “newfile.txt”)
## 8. Delete a File
import os
if os.path.exists(“newfile.txt”):
os.remove(“newfile.txt”)
## 9. Create a Folder
import os
os.mkdir(“datafolder”)
## 10. List Files in a Folder
import os
files = os.listdir(“.”)
print(files)
## 11. Copy Files
import shutil
shutil.copy(“sample.txt”, “backup_sample.txt”)
## 12. Move Files
import shutil
shutil.move(“sample.txt”, “datafolder/sample.txt”)
## 13. Open File in Binary Mode
Used for images, PDFs, etc.
Read binary:
with open(“image.png”, “rb”) as file:
data = file.read()
Write binary:
with open(“output.png”, “wb”) as file:
file.write(data)
## 14. Write Using Context Manager (Best Practice)
Exactly like you asked — same style as:
with open(“file.txt”, “w”) as file:
file.write(“content”)
Context manager ensures the file closes automatically.
🔥 Want real-time projects using file operations?
Examples available:
✅ Log reader
✅ Config loader
✅ File-based key-value store
✅ CSV processing
Just tell me!
Python JSON File Operations (Read, Write, Update, Append)
Using Python’s built-in json module.
## 1. Write JSON File
Creates a JSON file or overwrites if it exists.
import json
data = {
“name”: “Shanvi”,
“age”: 25,
“skills”: [“Python”, “ML”, “DevOps”]
}
with open(“data.json”, “w”) as file:
json.dump(data, file, indent=2)
Creates data.json:
{
“name”: “Shanvi”,
“age”: 25,
“skills”: [
“Python”,
“ML”,
“DevOps”
]
}
## 2. Read JSON File
import json
with open(“data.json”, “r”) as file:
data = json.load(file)
print(data)
print(data[“skills”])
## 3. Update JSON File
Load → modify → save back.
import json
# read
with open(“data.json”, “r”) as file:
data = json.load(file)
# update fields
data[“age”] = 26
data[“skills”].append(“AWS”)
# write back
with open(“data.json”, “w”) as file:
json.dump(data, file, indent=2)
## 4. Append Data to JSON File
JSON does not support direct append, so you must:
Read file
Update Python dictionary/list
Write again
Example: append a new object into a list.
import json
with open(“users.json”, “r”) as file:
users = json.load(file)
new_user = {“name”: “Ravi”, “age”: 30}
users.append(new_user)
with open(“users.json”, “w”) as file:
json.dump(users, file, indent=2)
## 5. Read JSON Lines (JSONL) File
Each line is a separate JSON object.
Example logs.jsonl:
{“event”:”start”,”time”:”10:00″}
{“event”:”stop”,”time”:”10:05″}
Parsing JSONL:
import json
with open(“logs.jsonl”, “r”) as file:
for line in file:
log = json.loads(line)
print(log)
## 6. Write Multiple JSON Objects (JSONL format)
import json
data = [
{“id”: 1, “msg”: “Hello”},
{“id”: 2, “msg”: “World”}
]
with open(“logs.jsonl”, “w”) as file:
for item in data:
file.write(json.dumps(item) + “\n”)
## 7. Convert Dictionary → JSON String
import json
data = {“a”: 1, “b”: 2}
json_string = json.dumps(data, indent=2)
print(json_string)
## 8. Convert JSON String → Python Dictionary
import json
json_str = ‘{“name”:”Shanvi”,”age”:25}’
data = json.loads(json_str)
print(data)
## 9. Handle Missing Keys
value = data.get(“address”, “not available”)
print(value)
## 10. Pretty Printing JSON
print(json.dumps(data, indent=4, sort_keys=True))
## 11. Check if JSON File Exists
import os
if os.path.exists(“data.json”):
print(“Exists”)
## 12. Delete JSON File
import os
if os.path.exists(“data.json”):
os.remove(“data.json”)
🚀 Want examples on real projects using JSON?
I can show:
✅ Storing user profiles
✅ API response parsing
✅ Logging system
✅ Config management
Just tell me!
1. Install PyYAML
#️⃣ 2. Read YAML File
Example config.yaml:
Python code to read YAML
Output
#️⃣ 3. Write YAML File
Python code
Creates a YAML file:
#️⃣ 4. Update YAML File
Load → modify → write back.
#️⃣ 5. Append New Section
#️⃣ 6. Load Multiple YAML Documents
YAML supports multiple docs in one file separated by ---.
Example multi.yaml:
Read all docs
#️⃣ 7. Dump Multiple YAML Docs
#️⃣ 8. Pretty Formatting
#️⃣ 9. Safe vs. Unsafe Loading
Always use:
Avoid: