41  Files Operation

41.1 Reading file

file_path: str = "context/hello.txt"

try: 
    with open(file_path, "r") as f:
        text: str = f.read()
    print(text)
except FileNotFoundError:
    print(f"File not found at {file_path}")
Hello, World!

Read only 5 bytes

with open(file_path, "r") as f:
        print(f.read(5)) # Read first 5 characters
        print(f.read(5)) # Read next 5 characters
        print(f.read())   # Read the rest of the file
Hello
, Wor
ld!

41.2 Read lines

Read line by line

with open(file_path, "r") as f:
    print(f.readline(), end="") # 1st line
    print(f.readline(), end="") # 2nd line
Hello, World!
Hi, there

Read all lines

with open(file_path, "r") as f:
    print(f.readlines()) # Read all lines into a list
['Hello, World!\n', 'Hi, there']

41.3 Append to File

file_path2: str = "context/hello-more.txt"
with open(file_path2, "a") as f:
    f.write("Hello, world!\n")
with open(file_path2, "a") as f:
    f.writelines(["Hello, world!\n", "Hello, world!\n"])

41.4 Overwrite to File

# Overwrite the file
with open(file_path2, "w") as f:
    f.write("New content\n")

41.5 Read JSON

41.5.1 Read from File

import json

with open("context/data.json", "r") as f:
    data: dict = json.load(f)
    
print(data)
{'name': 'Mario', 'age': 33, 'friends': ['Luigi', 'Toad'], 'other_info': None}

41.5.2 Write to JSON file

import json

data: dict = {'name': 'Bob', 'age': 43, 'job': None}

with open('context/new_json.json', 'w') as file:
    json.dump(data, file)
json.dumps(data) # convert to JSON string
'{"name": "Bob", "age": 43, "job": null}'