1. File read/write 1.1 read file
1 # Read (): Read all context from File 2 fp = open ('./data.txt')3 context = fp.read ()4 Fp.close ()
1.2 Read (), ReadLine (), ReadLines ()
Read (), reads everything from the open file object once and returns the string
ReadLine (), reads a line of content from the open file object each time, and then reads the pointer to the next line, so that all the content is read in
ReadLines (), reads everything from an open file object at once and stores the contents in a list, one element of the list is a read-in line of content
1 #Read (): Read all context from File2fp = open ('./data.txt')3Context =Fp.read ()4 fp.close ()5 6 #ReadLine (): Read one line at a time from file7fp = open ('./data.txt')8Context =Fp.readline ()9 fp.close ()Ten One #readlines (): Read all lines from file and Storte in list Afp = open ('./data.txt') -Context =Fp.readlines () -Fp.close ()
1.3 Writing Files
Write () writes the contents of the string to the file
Writelines () writes the list to a file, and all elements in the list are automatically merged
1 #write (): The file writen is string2fp = open ('./wf.txt','W')3Fp.write ('W, Hello World')4 fp.close ()5 6 #Writelines (): The file writen is List7fp = open ('./wf.txt','W')8Fp.writelines (['Writelines','Hello',' World'])9Fp.close ()
1.4 Closing Open File handles
In a computer program, an open file occupies a file handle, and the number of file handles owned by each process is limited, and the file handle occupies the computer resource. So when we finish the file, we need to close the file in time, in Python, close the open file using the close () method, usually using try: finally or with . as statement block to close the processed file object in a timely manner.
1 # Use finally sure file is closed 2 Try : 3 fp = open ('./data.txt')4 context = Fp.read () 5 finally : 6 Fp.close ()
1 # Use with sure file is closed 2 with open ('./data.txt') as FP:3 context = Fp.read ()
2. File reading and writing exercises
Python-File Read and write