2. Read a file
Calling open() with "r" returns a file object for reading. The file must already exist; otherwise Python raises FileNotFoundError.
A file object has three common reading methods:
read()with no arguments reads from the current position to the end of the file.readline()returns one line, including its trailing"\n". At the end of the file it returns an empty string"".readlines()returns a list of lines. Each line still includes its trailing"\n".- You can also loop directly over the file object:
for line in file:gives you one line at a time, again with the"\n".
If demo.txt contains Hello\n, then content is "Hello\n" and print(content) shows Hello. Call close() when you finish reading.
Coming from JavaScript? read() is like readFileSync(path, "utf8"). Python gives you a file object first, and you call the reading method on it.
Read the whole file
read() with no arguments reads everything from the current position to the end of the file and returns it as one string.
First write Hello, file! (without a newline) to /tmp/read.txt as you learned in the previous lesson, and close it. Then open the same path in "r" mode, call read(), close the file, and print the returned string.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read one line at a time
readline() returns the next line as a string, including its trailing newline. At the end of the file it returns an empty string.
Write first and second as two lines to /tmp/lines.txt (each line ends with \n), and close it. Open it in "r" mode and call readline() twice to get both lines. Close the file, then print each line after removing its newline with strip().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read all lines into a list
readlines() returns a list with every line in the file. Like readline(), it keeps the \n at the end of each line.
Write one and two as two lines to /tmp/list.txt, and close it. Open it in "r" mode, call readlines(), close the file, and print the list.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Loop over the lines
A file object is iterable: for line in file: gives you one line at a time, including the newline.
Write alpha, beta and gamma as three lines to /tmp/loop.txt, and close it. Open it in "r" mode and loop directly over the file object with for line in file:. Print each line after removing its newline. Do not call read(), readline() or readlines(). Close the file after the loop.
Print exactly:
Create a free account to save your progress and unlock chapter 2.