Quick copy-pasteables for writing and reading files in Python.
Entire files at once
def read_file(filename):
'''Reads a single number from a file'''
with open(filename, 'r') as f:
return f.read()
def write_file(filename, content, binary = False):
with open(filename, 'wb' if binary else 'w') as f:
f.write(content)
Line by line
def read_lines(filename):
with open(filename) as f:
for line in f:
print(line)
def write_lines(filename, lines):
with open(filename, 'w') as f:
for line in lines
print(f"{line}\n")