Python reads all the contents of a file once in the "Python" file read and write operation (click the Open link) has been explained, but sometimes you need to process each line in the file.
For example, there is a f:\1.txt as follows:
At this point, if you want to read this file by line, you can directly use the Pyhon for loop to read, where the for object is the file pointer, the code is as follows:
File_path= "F:\\a.txt" Fp=open (File_path, "A +"); for Eachline in FP: print Eachline.rstrip (); Fp.close ();
The results are as follows:
Here the Eachline is the content of each row, the following Rstrip () method is used to eliminate the \ n characters, so that print printing beautiful, and more importantly, let your eachline variable is not the end of \ n. If there is no Rstrip (), the results of the above program will become the following. The Strip () here is equivalent to the trim () method in Java, C #. Strip is to trim the whitespace, line breaks, and so on, on both sides of the string. Lstrip is trim off the left side of the space, line breaks, etc., Rstrip, is trim off the right side of the left side of the space, line break, and so on, anyway, is to get rid of blank things.
Also, note that the file path, although written in Python file_path= "F:\a.txt", Pydev compiler will not error, but at run time, will appear the following [Errno] Invalid mode (' A + ') or FileName is wrong, so you should still write file_path= "F:\\a.txt", otherwise Python will turn \a into something you don't know.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Python" reads the file by line, IOError: [Errno] Invalid mode (' A + ') or filename, the line break of the file is processed