Python is easy to read the contents of a text file into a string variable that can be manipulated. The file object provides three read methods:. Read (),. ReadLine (), and. ReadLines (). Each method can accept a variable to limit the amount of data read at a time, but they usually do not use a variable. read () reads the entire file at a time, and is typically used to place the contents of the file in a string variable. However, the. Read () generates the most direct string representation of a file's content, but it is unnecessary for sequential row-oriented processing and is not possible if the file is larger than available memory
Open File
print "Opening and closing the file."
text_file = open ("Read_it.txt", "R")
Text_file.close ()
Read one line
print "nreading one line at a time."
text_file = open ("Read_it.txt", "R")
Print Text_file.readline ()
Print Text_file.readline ()
Print Text_file.readline ()
Text_file.close ()
Read a character
print "nreading characters from a line."
text_file = open ("Read_it.txt", "R")
Print Text_file.readline (1)
Print Text_file.readline (5)
Text_file.close ()
Read the entire file output
Print "nreading the entire file into a list."
text_file = open ("Read_it.txt", "R")
lines = Text_file.readlines ()
Print lines
Print Len (lines)
For line in lines:
Print Line
Text_file.close ()
Read a file in one line
print "nlooping through the file, line by line."
text_file = open ("Read_it.txt", "R")
For line in Text_file:
Print Line
Text_file.close ()
Introduction to the Open function used above
F=open ('/tmp/hello ', ' W ')
#open (path + filename, read-write mode)
#读写模式: R Read Only, r+ read/write, w New (will overwrite original file), a append, b binary file. Common patterns