Python: Read File
Read entire file
fileObject.read()
# Read entire file import sys import os xpath = os.path.expanduser("~/xtest.txt") xtext = "Alice was beginning to get very tired." # write file, overwrite exsiting xfile = open(xpath, "w", encoding="utf-8") xfile.write(xtext) xfile.close() # s------------------------------ # 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
# Read one line at a time import sys import os xpath = os.path.expanduser("~/xtest.txt") xtext = """one two three infinity""" # write file, overwrite exsiting xfile = open(xpath, "w", encoding="utf-8") xfile.write(xtext) xfile.close() # s------------------------------ # open file, read mode xfile = open(xpath, "r", encoding="utf-8") for xline in xfile: print(xline, end="") # one # two # three # infinity xfile.close()
Read entire file as a list of lines
fileObject.readlines()
# read entire file as a list of lines import sys import os xpath = os.path.expanduser("~/xtest.txt") xtext = """one two three infinity""" # write file, overwrite exsiting xfile = open(xpath, "w", encoding="utf-8") xfile.write(xtext) xfile.close() # s------------------------------ # open file, read mode xfile = open(xpath, "r", encoding="utf-8") xlines = xfile.readlines() for x in xlines: print(x, end="") # one # two # three # infinity xfile.close()
Using with-statement
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.