0% found this document useful (0 votes)
2 views3 pages

Python File Json Cheatsheet

This document serves as a quick reference for file handling and JSON in Python. It outlines file modes, methods, and best practices for file operations, as well as functions for working with JSON data, including type mapping and common patterns. Key rules emphasize safe file handling, proper JSON formatting, and error management.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Python File Json Cheatsheet

This document serves as a quick reference for file handling and JSON in Python. It outlines file modes, methods, and best practices for file operations, as well as functions for working with JSON data, including type mapping and common patterns. Key rules emphasize safe file handling, proper JSON formatting, and error management.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Cheat Sheet

File Handling & JSON — quick reference

1. File Handling

File Modes

Mode Meaning

"r" read only (error if missing)

"w" write/overwrite (creates file, DESTROYS old content)

"a" append to end (creates file, old content safe)

"r+" read + write (error if missing)

"rb" / "wb" binary (images, PDFs)

Methods
• [Link]() → entire file as one string
• [Link]() → one line (keeps \n)
• [Link]() → list of lines (each keeps \n)
• [Link](text) → write string (no auto \n)
• [Link](list) → write list (no auto \n)
• [Link](0) → move cursor to start
• .strip() → remove whitespace + \n
• enumerate(list, 1) → loop with index and item

Patterns
Standard open
with open("[Link]", "w") as f:
[Link]("Hello\n")

Safe read
try:
with open("[Link]", "r") as f:
lines = [Link]()
except FileNotFoundError:
print("File not found.")

Search with flag


found = False
for line in lines:
if [Link]() in [Link]():
print(f"Found: {[Link]()}")
found = True
break
if not found: print("Not found.")
Rules
• Always use with open() — never call [Link]() manually
• "w" DESTROYS existing content — use "a" to add safely
• readlines() keeps \n — always .strip() when printing
• writelines() needs \n manually inside each string
• Flag variable: set found=False before loop, check after loop
• .lower() on both sides for case-insensitive search
• Wrap int(input()) in try/except ValueError
• Variable names: lowercase_snake_case only (PEP 8)

2. JSON

4 Functions (s = string, no s = file)

Function Purpose

[Link]() dict to JSON string (memory)

[Link]() JSON string to dict (memory)

[Link]() dict to JSON file

[Link]() JSON file to dict

Type Mapping

Python JSON

dict object {}

list array []

str "string"

int / float number

True / False true / false (auto-converted)

None null

Patterns
import json

[Link](data, indent=4) # dict → string


[Link](json_string) # string → dict

with open("[Link]", "w") as f: # dict → file


[Link](data, f, indent=4)

with open("[Link]", "r") as f: # file → dict


data = [Link](f)
Load → Modify → Save
with open("[Link]","r") as f: data = [Link](f)
data["key"] = "new_value"
data["tags"].append("new_tag")
with open("[Link]","w") as f: [Link](data, f, indent=4)

Safe load
try:
with open("[Link]","r") as f: return [Link](f)
except (FileNotFoundError, [Link]):
return []

Nested access
data["address"]["city"]
data["skills"][1]
data["experience"][1]["company"]

Rules
• s = string (memory), no s = file. That's it.
• Once loaded, JSON is just a normal Python dict
• All JSON keys and string values need double quotes
• Always wrap file ops in try/except
• Safe default pattern: except → return [] keeps program alive
• .lower() on both sides for case-insensitive search
• Use single quotes inside f-strings: f"{d['key']}"
• Menu input → plain input(), not int(input())

You might also like