"""Reading files"""

# We should have all files we need in the same folder/directory
# as this python script file
# budgie_budget.csv should be in the same folder as this python file

# How do we open a file?

# type of arguments - file_to_open: str, mode: str -> TextIO
# The mode can be either 'r' for reading or 'w' for writing
budgie_file = open('budgie_budget.csv', 'r')

# when we're done working with a file that we've opened,
# then we should 'close' it 
budgie_file.close()

# You don't want to leave files open
# especially when writing to a file - won't save unless you close it

# 1. for line in file
budgie_file = open('budgie_budget.csv', 'r')
for line in budgie_file:
    # do whatever we want to each line in the file
    print(line)
    # we'll see blank lines between each line in the file
    # because each line ends with \n and print adds a \n

line_after_for_loop = budgie_file.readline()


budgie_file.close()

# 2. read method
# reads the entire file into one giant string
budgie_file = open('budgie_budget.csv', 'r')

file_contents = budgie_file.read()
print(file_contents)
print(len(file_contents))
print(file_contents.count('\n'))

line_after_read = budgie_file.readline()


budgie_file.close()


# 3. readlines method
# reads all lines into a list of strings
budgie_file = open('budgie_budget.csv', 'r')
print(budgie_file.readlines())
line_after_read_lines = budgie_file.readline()

budgie_file.close()

# 4. readline
budgie_file = open('budgie_budget.csv', 'r')

print('START readline()')
print(type(budgie_file.readline()))
print(budgie_file.readline())
print(budgie_file.readline())
print(budgie_file.readline())
print(budgie_file.readline())
print(budgie_file.readline())
print(budgie_file.readline())
print(budgie_file.readline())
no_line_to_read = budgie_file.readline()
print('END readline()')

# Every time we read a line in a file, we can't go back.
# To start over, we would have to close and reopen the file.
budgie_file.close()
budgie_file = open('budgie_budget.csv', 'r')

print(budgie_file.readline())
budgie_file.close()


## Writing files
# mode 'w' will overwrite file
budgie_file = open('budgie_budget.csv', 'w')
budgie_file.write('\nbudgie, $90')
budgie_file.close()

# mode 'a' will append to the end of the file, keeping original contents
budgie_file = open('budgie_budget.csv', 'a')

budgie_file.write('\ngolden budgie, $10000')

budgie_file.close()

budgie_file = open('budgie_budget.csv', 'r')

file_contents = budgie_file.read()

budgie_file.close()



