6-File

Sun 29 June 2025
#Basic File Reading/Writing
f = open("sample.txt", "w")
f.write("Hello")
f.close()
f = open("sample.txt", "r")
print(f.read())
f.close()
Hello
with open("sample.txt", "r") as f:
    print(f.read())
Hello
with open("sample.txt", "w") as f:
    f.write("New content")
with open("sample.txt", "a") as f:
    f.write("\nAppended line")
with open("sample.txt", "r") as f:
    print(f.readline())
New content
with open("sample.txt", "r") as f:
    print(f.readlines())
['New content\n', 'Appended line']
with open("sample.txt", "r") as f:
    for line in f:
        print(line.strip())
New content
Appended line
with open("sample.txt", "r") as f:
    data = f.read(5)
    print(data)
New c
with open("sample.txt", "r") as f:
    f.seek(0)
    print(f.read(4))
New
with open("sample.txt", "r") as f:
    print(f.tell())  # cursor position
0
with open("sample.txt", "r") as f:
    f.seek(2)
    print(f.read(3))
w c
with open("sample.txt", "r") as f:
    for i, line in enumerate(f):
        print(f"{i}: {line.strip()}")
0: New content
1: Appended line
try:
    with open("not_exist.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("File not found")
File not found
with open("sample.txt", "w+") as f:
    f.write("Test")
    f.seek(0)
    print(f.read())
Test
with open("sample.txt", "a+") as f:
    f.write("\nAgain")
    f.seek(0)
    print(f.read())
Test
Again
with open("sample.txt", "r") as f:
    chars = list(f.read())
    print(chars)
['T', 'e', 's', 't', '\n', 'A', 'g', 'a', 'i', 'n']
with open("sample.txt", "r") as f:
    words = f.read().split()
    print(words)
['Test', 'Again']
lines = ["Line1\n", "Line2\n", "Line3\n"]
with open("sample.txt", "w") as f:
    f.writelines(lines)
with open("sample.txt", "r") as f:
    print(f.read().upper())
LINE1
LINE2
LINE3
with open("sample.txt", "r") as f:
    print(f.read().lower())
line1
line2
line3
with open("sample.txt", "r") as f:
    print(f.read().splitlines())
['Line1', 'Line2', 'Line3']
with open("sample.txt", "r") as f:
    lines = f.readlines()
    print(lines[::-1])  # reversed
['Line3\n', 'Line2\n', 'Line1\n']
with open("sample.txt", "r") as f:
    print(sum(1 for _ in f))  # line count
3
with open("sample.txt", "r") as f:
    print(len(f.read().split()))  # word count
3
with open("sample.txt", "r") as f:
    print(len(f.read()))  # char count
18
with open("sample.txt", "r") as f:
    longest = max(f, key=len)
    print(longest.strip())
Line1
with open("sample.txt", "r") as f:
    for line in f:
        if "Line" in line:
            print(line.strip())
Line1
Line2
Line3
with open("sample.txt", "r") as f:
    print(any("Line2" in line for line in f))
True
with open("sample.txt", "r") as f:
    print(all("Line" in line for line in f))
True
#File Paths, Encodings, Errors
with open("sample.txt", encoding="utf-8") as f:
    print(f.read())
Line1
Line2
Line3
try:
    with open("sample.txt", "x") as f:
        f.write("new file")
except FileExistsError:
    print("Already exists")
Already exists
import os
print(os.path.exists("sample.txt"))
True
os.remove("sample.txt")
with open("newfile.txt", "w") as f:
    f.write("temporary")
os.rename("newfile.txt", "renamed.txt")
os.mkdir("test_dir")
os.rmdir("test_dir")
print(os.getcwd())
C:\tact\pynotes\notebooks\basics
os.chdir("..")
print(os.getcwd())
C:\tact\pynotes\notebooks
from pathlib import Path
print(Path("sample.txt").exists())
False
Path("sample.txt").write_text("Written by pathlib")
18
Path("sample.txt").unlink()  # delete
Path("folder").mkdir(exist_ok=True)
Path("folder/sample.txt").write_text("In folder")
9
p = Path("folder/sample.txt")
print(p.name, p.suffix, p.stem)
sample.txt .txt sample
print(p.parent)
folder
print(list(Path(".").glob("*.txt")))
[]
print(p.resolve())
C:\tact\pynotes\notebooks\folder\sample.txt
with open("binary.bin", "wb") as f:
    f.write(b"binary data")
with open("binary.bin", "rb") as f:
    print(f.read())
b'binary data'
with open("sample.txt", "w", errors="ignore") as f:
    f.write("ignored")
Path("utf.txt").write_text("नमस्ते", encoding="utf-8")
6
print(Path("utf.txt").read_text(encoding="utf-8"))
नमस्ते
print("utf.txt" in os.listdir())
True
print(os.listdir("."))
['basics', 'binary.bin', 'folder', 'pandas-work', 'sample.txt', 'utf.txt']
print([f for f in os.listdir() if f.endswith(".txt")])
['sample.txt', 'utf.txt']
Path("file_with_space.txt").write_text("spacing")
7
with open("file_with_space.txt", "r") as f:
    print(f.read().replace(" ", "_"))
spacing
with open("sample.txt", "a") as f:
    f.write("\nLast line")
#CSV, JSON, Pickle
import csv
with open("data.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Alice", 30])
with open("data.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
['Name', 'Age']
['Alice', '30']
import json
data = {"name": "Alice", "age": 30}
with open("data.json", "w") as f:
    json.dump(data, f)
with open("data.json", "r") as f:
    print(json.load(f))
{'name': 'Alice', 'age': 30}
print(json.dumps(data)) 
{"name": "Alice", "age": 30}
print(json.loads('{"key": 1}'))
{'key': 1}
with open("data.json", "w") as f:
    json.dump(data, f, indent=4)
import pickle
with open("data.pkl", "wb") as f:
    pickle.dump(data, f)
with open("data.pkl", "rb") as f:
    print(pickle.load(f))
{'name': 'Alice', 'age': 30}
try:
    with open("non_existing.txt", "r") as f:
        pass
except FileNotFoundError as e:
    print(e)
[Errno 2] No such file or directory: 'non_existing.txt'
#Advanced/Tricks/Useful Patterns
with open("numbers.txt", "w") as f:
    f.write("\n".join(str(i) for i in range(10)))
with open("numbers.txt", "r") as f:
    print([int(line) for line in f])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
with open("file.txt", "w") as f:
    pass  # creates empty file
print(os.stat("file.txt").st_size)  # file size
0
with open("log.txt", "a") as f:
    f.write("Log entry\n")
with open("multi.txt", "w") as f:
    f.write("Line1\nLine2\nLine3\n")
with open("multi.txt") as f:
    print(f.readlines()[1])  # second line
Line2
lines = Path("multi.txt").read_text().splitlines()
print(lines[-1])  # last line
Line3
lines[1] = "Updated line2"
Path("multi.txt").write_text("\n".join(lines))
25
with open("read.txt", "w") as f:
    f.write("123abc456")
with open("read.txt", "r") as f:
    print("abc" in f.read())
True
f = open("late.txt", "w")
f.write("oops")
f.close()
with open("late.txt", "r+") as f:
    f.seek(0)
    f.write("fixed")
with open("space.txt", "w") as f:
    f.write("   line with space   ")
with open("space.txt") as f:
    print(f.read().strip())
line with space
with open("csv2.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=["id", "score"])
    writer.writeheader()
    writer.writerow({"id": 1, "score": 90})
with open("csv2.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["score"])
90
with open("utf8.txt", "w", encoding="utf-8") as f:
    f.write("¡Hola!")
with open("utf8.txt", encoding="utf-8") as f:
    print(f.read())
¡Hola!
Path("delete_me.txt").write_text("bye")
Path("delete_me.txt").unlink()
try:
    Path("badfile.txt").read_text()
except FileNotFoundError:
    print("No such file")
No such file
with open("even.txt", "w") as f:
    f.writelines([f"{i}\n" for i in range(0, 10, 2)])
with open("even.txt") as f:
    evens = [int(line) for line in f]
    print(evens)
[0, 2, 4, 6, 8]
print(os.path.abspath("sample.txt"))
C:\tact\pynotes\notebooks\sample.txt
print(os.path.basename("folder/sample.txt"))
sample.txt
print(os.path.dirname("folder/sample.txt"))
folder
print(os.path.splitext("file.txt"))  # ('file', '.txt')
('file', '.txt')
print(Path("folder/file.txt").with_suffix(".bak"))
folder\file.bak
with open("caps.txt", "w") as f:
    f.write("hello\nworld")
with open("caps.txt") as f:
    print([line.upper() for line in f])
['HELLO\n', 'WORLD']


Score: 105

Category: basics