The simplest way to iterate over a file line-by-line:
with open('myfile.txt', 'r') as fp: for line in fp: print(line)
readline() allows for more granular control over line-by-line iteration. The example below is equivalent to the one above:
with open('myfile.txt', 'r') as fp: while True: cur_line = fp.readline()
# If the result is an empty string if cur_line == '': # We have reached the end of the file break print(cur_line)
Using the for loop iterator and readline() together is considered bad practice.
More commonly, the readlines() method is used to store an iterable collection of the file's lines:
with open("myfile.txt", "r") as fp: lines = fp.readlines() for i in range(len(lines)): print("Line " + str(i) + ": " + line)
This would print the following:
Line 0: hello
Line 1: world
Section 30.3: Iterate files (recursively)
To iterate all files, including in sub directories, use os.walk:
import os for root, folders, files in os.walk(root_dir): for filename in files: print root, filename
root_dir can be "." to start from current directory, or any other path to start from.
Python 3.x Version ≥ 3.5
If you also wish to get information about the file, you may use the more efficient method os.scandir like so:
for entry in os.scandir(path): if not entry.name.startswith('.') and entry.is_file(): print(entry.name)
Getting the full contents of a file
The preferred method of file i/o is to use the with keyword. This will ensure the file handle is closed once the reading or writing has been completed.
with open('myfile.txt') as in_file: content = in_file.read()
print(content)
or, to handle closing the file manually, you can forgo with and simply call close yourself:
in_file = open('myfile.txt', 'r') content = in_file.read() print(content)
in_file.close()
Keep in mind that without using a with statement, you might accidentally keep the file open in case an unexpected exception arises like so:
in_file = open('myfile.txt', 'r') raise Exception("oops") in_file.close() # This will never be called