"Python" reads the file by line, IOError: [Errno] Invalid mode (' A + ') or filename, the line break of the file is processed

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.