Python: Read File

By Xah Lee. Date: . Last updated: .

To open a file and and read file:

import sys

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

# read whole file
xtext =

Read entire file
Read one line at a time
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:

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 Text Processing