简体   繁体   中英

Reading specific data from a text file in python

I have a text file which is two columns of data with headers(the header is "x" and " xy data"). How can I read only the second column from the forth line to the end of the file(in order to skip the headers)? I only need the numbers. I need a simple solution as I need to use this code in ABAQUS scripting. Here is my text file:

              X              XYData-201   

            0.                 0.         
            3.99845E-03        0.         
            7.98118E-03        0.         
           11.9483E-03         0.         

You can turn a string like

"            11.9483E-03         0.           "

into the list [0.011948, 0.0] by doing the following (assuming s is the above string)

map(float, s.split())

Broken down into steps:

  • s.split() breaks a string down into an array of sub-strings by splitting at whitespace turning s in this example to ['11.9483E-03', '0.']

  • map(float, s.split()) takes the array above and turns into the list [0.011948, 0.0] by converting every element into a float.

If you need just the number at the second column, you can just do:

float(s.split()[1])

So assuming the file is name blah.txt, to read all the numbers in the second column when they start from the fourth line onwards, you do:

 with open('blah.txt', 'r') as f:
     for i, line in enumerate(f):
         if i < 4:
             continue  # we are in line 1-3, skip
         print float(line.split()[1])

If you want a list of all the numbers in the second column, you can use a list comprehension:

 numbers = [float(line.split()[1]) for line in open('blah.txt', 'r').readlines()[4:]]

(Note: The assumes you are working with Python 2.7, or else map will not return a list, and print will require parentheses)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM