Python: Read File
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
.