# Author: Scott Wehrwein
# Date: 11/22/2019
# Demo of various methods of file objects that
# are used to read strings from a file.


# To demo:
# read(size) - read the next size characters from the file
# read() - read the entire file into a string
# readlines() - return a list of lines of the file
# seek(location) - move the cursor to location in the file
# tell() - return the current location of the file

# demo for iterating over lines of a file:
file_obj = open("test.txt", 'r')
for line in file_obj:
    print(line)

file_obj.close()
# Notice: newline characters come with each line
#       use line.strip("\n") to remove

# To get the lines as they're iterated over above, but in
# list form, you can use readlines():
file_obj = open("test.txt", "r")
all_lines = file_obj.readlines()
file_obj.close()

# each element of all_lines is now a line of the file.
# as before, newlines are not removed.


# demo for seek, read, and tell.

# For the example's sake, suppose test_short.txt contains:
# Never gonna give you up
fobj = open("test_short.txt", "r")
print(fobj.read(3)) # Nev
print(fobj.read(4)) # er g
fobj.seek(2) # cursor is now at index 2, so 'v' is the next character to be read

# read with no argument prints the rest of the file,
# starting at the current cursor location:
print(fobj.read()) # ver gonna give you up

# tell returns the current cursor position
fobj.seek(10) # seek back to position 10
print(fobj.tell()) # 10

# extra - won't be on the exam, but is useful:
#with open("test.txt") as file_obj:
#    for line in file_obj:
#        print(line)

# file_obj is automatically closed when we exit the
# indented block of the with statmement