f = open(/Users/katrinerk/Desktop/pg1062.txt")
for line in f:
print( line )
f.close()
f = open(r"C:\Desktop\pg1062.txt")
# “open” takes as its argument a file name, which may include directory information.
# Do not forget to start with the “open” command!
#
You need the file object that it returns to read the file.
f = open("/Users/katrinerk/Desktop/pg1062.txt")
# “open” returns a file object. This, then, can be used to access the file contents.
>>> type(f)
<class '_io.TextIOWrapper'>
# We can iterate through the lines of a file as if it were a list.
# Note that "line" is just a variable name. I could have named it anything else.
“line” is a variable that will be filled by each line of the file in turn.
# After reading the file, you close the file object.
This is not strictly necessary if you are only reading the file
# -- if you are writing, it is necessary -- but it is good practice.
# read a file line by line
f = open("
/Users/katrinerk/Desktop/
pg1062.txt")
f.close
# read the whole file in one go, as a string
f = open("/
Users/katrinerk/Desktop/
myfilecontents = f.read()
# read the next line of the file
f = open(
line1 = f.readline() # reads the first line
# at this point the “file reading pointer”
# points to the second line
line2 = f.readline() # reads the second line
line3 = f.readline() # reads the third line
num_lines = 0
f = open("~/Desktop/pg1062.txt")
num_lines = num_lines + 1
print( num_lines )
# num_lines will count lines.num_lines = 0
# inside_raven will signal if we are inside the poem "The Raven"
inside_raven = False
f = open("/Users/katrinerk/Desktop/1epoe10.txt") # Contains several stories by E.A. Poe
if not(inside_raven) and line.startswith(“The Raven”):
# “The Raven” starts here. Start counting.
inside_raven = True
num_lines = num_lines + 1
elif inside_raven and line.startswith("The Masque of the Red Death"):
# “The Raven” has ended. Remember this in the variable inside_raven
inside_raven = False
elif inside_raven:
# We are inside “The Raven”. Go on counting.
Again, we make a file object with “open”. Only this time we give two
arguments.
# The second one is “w” for “write”.
# So we have to decide at
the time when we open a file whether we want to read it
# or write to it.
f = open("myoutfile", "w
"
)
# We use the "print" command to write to a file, but with the additional
parameter file=f.
# Note that f is the variable in which we put the file object.
# If I had named the file object "bob", it would have been "print(..., file = bob)"
print("Hello", file=f)
print("Writing another line to the file.", file = f)
print("Here’s a number:", 5, file= f)
# And close the file.
# pickling functionality is not loaded by default; you have to import it
import pickle
mylist
= [ 1,2,3,4,5]
f = open("file_mylist.data", "w")
pickle.dump(mylist, f)
f = open("file_mylist.data")
newlist = pickle.load(f)