How to read in the contents of a file in Python.
def rememberer(thing):
with open("database.txt", "a") as file:
file.write(thing+"\n")
def show():
with open("database.txt") as file:
for line in file:
print(line)
if __name__ == '__main__':
if sys.argv[1].lower() == '--list':
show()
else:
rememberer(' '.join(sys.argv[1:]))
Run the following command to automatically add an item to the file:
python remember.py juice boxes
Reading Command
You can control the number of bytes read by passing in an integer.
with open("my_file.txt", "r") as file:
file.read(10)
file.read(bytes=-1)
would read the entire contents of the file.
file.seek()
Relatedly, will move the read/write pointer to another part of the file.
file.readlines()
Reads the entire file into a list, with each line as a list item.