Python Reading Files

To read a file in Python, you need to open the file using the built-in open() function.

After opening the file, you can use read() method to read the file. If you call read() method without any argument, it reads the entire file. If you specify a numeric argument, read() method reads the specified number of characters from the file.

Consider we have the following file:

demo_file.txt
This is a test file
for demonstrating read()
function in Python. 

Reading the entire file:

f = open("demo_file.txt", "r")
content = f.read()
print(content)          # prints:
                        # This is a test file
                        # for demonstrating read()
                        # function in Python.
f.close()

Reading the first 14 characters from the file:

f = open("demo_file.txt", "r")
content = f.read(14)
print(content)          # prints:
                        # This is a test
f.close()

With Statement

If you open the file using with statement, you do not have to call close() method explicitly. You can rewrite the previous code again using with statement as follows:

with open("demo_file.txt", "r") as f:
    content = f.read(14)

    print(content)

Reading Lines

To read a file line-by-line, you can use readline() method.

with open("demo_file.txt") as f:
    print(f.readline())          # This is a test file
    print(f.readline())          # for demonstrating read()

You can also use a for loop to read the entire file line-by-line.

with open("demo_file.txt") as f:
    for line in f:
        print(line)              # reads the file line-by-line
SHARE