To do work with files there is a concept of context magagers that is usefull to look at. The reason is that we must remember to open/close files as shown below:
fname = "myfile.txt" # Name of file
# 1. Opening, reading and closing file
FILE = open(fname)
for line in FILE:
print(line)
FILE.close()
# 2. Use the 'with' context manager to manage opening/closing
with open(fname) as FILE:
for line in FILE:
print(line)
Now that we want read in data we must clearly add it to a variable
fname = "myfile.txt" # Name of file
# 1. Read data, simple
with open(fname) as FILE:
data = []
for line in FILE:
data.append(line)
# 2. Read data directly into the variable
with open(fname) as FILE:
data = list(FILE)
Maybe we want to strip 'newlines' at the end, this we can do by "stripping" the '\n'
character:
fname = "myfile.txt" # Name of file
# 1. Read data and strip 'newlines', simple
with open(fname) as FILE:
data = []
for line in FILE:
data.append( line.rstrip() )
# 2. Read data and strip newlines using `map` function
with open(fname) as FILE:
data = map(str.rstrip, FILE)
Finally, we want to get a few specific lines. This we can do with a simple if statement:
fname = "myfile.txt" # Name of file
readLines = [0, 2, 4] # Lines to be read from file, zero indexed
# 1. Read data from specific lines and strip 'newlines', simple
with open(fname) as FILE:
data = []
for line in FILE:
if idx in readLines:
data.append( line.rstrip() )
# 2. Read data from specific lines and strip newlines using 'list comprehension'
with open(fname) as FILE:
data = [ line.rstrip() for idx, line in enumerate(FILE) if idx in readLines ]