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!
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 fileHello
, Wor
ld!
Read line by line
with open(file_path, "r") as f:
print(f.readline(), end="") # 1st line
print(f.readline(), end="") # 2nd lineHello, 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']
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"])# Overwrite the file
with open(file_path2, "w") as f:
f.write("New content\n")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}
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}'