Python implementation readline remove newline characters \ n

Source: Internet
Author: User
Tags readline
Just using Python's readline (s) to read the discovery of the file will always appear in the format of some small errors, and then think of it because the file newline characters and other symbols (\n\r\t) will also be readline (s) to read, the following is the small method I use

Give me a chestnut, here's my file:

In [1]: cat /tmp/ip.txt111.231.0.0/16122.152.0.0/16140.143.0.0/1659.110.0.0/16106.75.0.0/16

Read the file into the variable F, and then execute Redline Discovery, which also includes a newline character ' \ n ':

In [2]: f = open("/tmp/ip.txt",‘r‘)In [3]: f.readline()Out[3]: ‘111.231.0.0/16\n‘

We can cut the required content through the split method to get the following result, but it's not what we really want, and the result is a list:

In [4]: f.readline().split("\n")Out[4]: [‘122.152.0.0/16‘, ‘‘]

In the end, we can retrieve the previous content by index, and then send this content to other processes for processing.

In [5]: f.readline().split("\n")[0]Out[5]: ‘140.143.0.0/16‘

Perhaps some classmates will ask, that \r\t\n all exist situation?
Then we're going to just let them disappear.

Python implementation readline remove newline characters \ n

Related Article

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.