Python: Read File

By Xah Lee. Date: . Last updated: .

Read entire file

fileObject.read()

import sys
import os

xpath = os.path.expanduser("~/xtest.txt")

# write file, overwrite exsiting file
xfile = open(xpath, "w", encoding="utf-8")
xfile.write("Alice was beginning to get very tired. 🧑")
xfile.close()

# HHHH------------------------------

# open file
xfile = open(xpath, "r", encoding="utf-8")

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

print(xtext)
# Alice was beginning to get very tired. 🧑

Read one line at a time

import sys
import os

xpath = os.path.expanduser("~/xtest.txt")

# write file, overwrite exsiting
xfile = open(xpath, "w", encoding="utf-8")
xfile.write(
    """🧑 U+1F9E1: ORANGE HEART
πŸ’› U+1F49B: YELLOW HEART
πŸ’š U+1F49A: GREEN HEART
πŸ’™ U+1F499: BLUE HEART
πŸ’œ U+1F49C: PURPLE HEART
🀍 U+1F90D: WHITE HEART
🀎 U+1F90E: BROWN HEART"""
)
xfile.close()

# HHHH------------------------------

# open file, read mode
xfile = open(xpath, "r", encoding="utf-8")

for xline in xfile:
    print(xline, end="")

# 🧑 U+1F9E1: ORANGE HEART
# πŸ’› U+1F49B: YELLOW HEART
# πŸ’š U+1F49A: GREEN HEART
# πŸ’™ U+1F499: BLUE HEART
# πŸ’œ U+1F49C: PURPLE HEART
# 🀍 U+1F90D: WHITE HEART
# 🀎 U+1F90E: BROWN HEART

xfile.close()

Read entire file as a list of lines

fileObject.readlines()

import sys
import os

xpath = os.path.expanduser("~/xtest.txt")

# write file, overwrite exsiting
xfile = open(xpath, "w", encoding="utf-8")
xfile.write(
    """🧑 U+1F9E1: ORANGE HEART
πŸ’› U+1F49B: YELLOW HEART
πŸ’š U+1F49A: GREEN HEART
πŸ’™ U+1F499: BLUE HEART
πŸ’œ U+1F49C: PURPLE HEART
🀍 U+1F90D: WHITE HEART
🀎 U+1F90E: BROWN HEART"""
)
xfile.close()

# HHHH------------------------------

# open file, read mode
xfile = open(xpath, "r", encoding="utf-8")

xlines = xfile.readlines()

for x in xlines:
	print(x, end="")

# 🧑 U+1F9E1: ORANGE HEART
# πŸ’› U+1F49B: YELLOW HEART
# πŸ’š U+1F49A: GREEN HEART
# πŸ’™ U+1F499: BLUE HEART
# πŸ’œ U+1F49C: PURPLE HEART
# 🀍 U+1F90D: WHITE HEART
# 🀎 U+1F90E: BROWN HEART

xfile.close()

Using β€œwith” to Open File

Alternatively, you can use with:

# example of opening file, using with

with open("c:/Users/xah/xtest.txt", "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