How to read a file in a text. txt format in Python

Source: Internet
Author: User

The interception section reads as follows:

10.235186    11.321997 10.122339    11.810993 9.190236     8.904943 9.306371     9.847394 8.330131     8.340352

How do I turn data into a matrix?

The first step is to open the file by using the open () function:

1 >>> filename='; 2 >>> fr=open (fileName);

View Type:

1>>> fr=open (fileName);2>>>Type (FR)3<class '_io. Textiowrapper'>4>>>FR5<_io. Textiowrapper name='D://softwaretool/python/python_exercisecode/chap13_pca//testset.txt'Mode='R'encoding='cp936'>

The 2nd step reads by line:

Such as:

1 >>> delim='\ t'; 2 >>> line0=fr.readlines (); 3 >>> type (LINE0)4 <class'list' >5 >>> line0[0]6'10.235186\t11.321997\n '

Then use strip and split processing:

1 >>> line1=line0[0].strip ()2 >>> line13' 10.235186\t11.321997 ' 4 >>> line2=Line0[0].strip () split (Delim)5 >>> line2 6 ['10.235186'11.321997']

The 3rd step converts the string form into the data form of the float type:

1  for inch Line2]; 2 >>> line33 [10.235186, 11.321997]

How to read a file in a text. txt format in Python

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.