Python: Read File

By Xah Lee. Date: . Last updated: .

Read File

fileObject.read()
Read entire file
import sys

xfile = open("c:/Users/xah/xx.html", "r", encoding="utf-8")

# read whole file
xtext = xfile.read()
xfile.close()

print(xtext)
fileObject.readline()
Read one line at a time
fileObject.readlines()
Read entire file as a list of lines

Using โ€œwithโ€ to Open File

Alternatively, you can use with:

# example of opening file, using ใ€Œwithใ€

with open("/home/joe/file.html", "r") as f:
    for x in f:
        print(x)

When using with, you do not need to close the file. Python will close any file opened within it, when the with block is done.

2013-11-29 thank to Kurt Schwehr for showing me with.

Python, Read Write File