str = "context/hello.txt"
file_path:
try:
with open(file_path, "r") as f:
str = f.read()
text: print(text)
except FileNotFoundError:
print(f"File not found at {file_path}")
Hello, World!
str = "context/hello.txt"
file_path:
try:
with open(file_path, "r") as f:
str = f.read()
text: 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!
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']
str = "context/hello-more.txt" file_path2:
with open(file_path2, "a") as f:
"Hello, world!\n") f.write(
with open(file_path2, "a") as f:
"Hello, world!\n", "Hello, world!\n"]) f.writelines([
# Overwrite the file
with open(file_path2, "w") as f:
"New content\n") f.write(
import json
with open("context/data.json", "r") as f:
dict = json.load(f)
data:
print(data)
{'name': 'Mario', 'age': 33, 'friends': ['Luigi', 'Toad'], 'other_info': None}
import json
dict = {'name': 'Bob', 'age': 43, 'job': None}
data:
with open('context/new_json.json', 'w') as file:
file) json.dump(data,
# convert to JSON string json.dumps(data)
'{"name": "Bob", "age": 43, "job": null}'