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 = xfile.read()
xfile.close()

print(xtext)
fileObject.read()
Read entire file
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 Text Processing

Python

Overview

Help

Comment

String

Arithmetic

Boolean

Conditional

Loop

Data Structure

Function and Class

Module

Misc

Regex

Text Processing

Web

Misc