0

I am new to python. I am trying to read each line from a file and then for each line, I have to first read a string and then a series of floats. How can I do this using python-2.7? An example of the text file:

phon_R01_S01_1    119.99200    157.30200    74.99700
phon_R01_S01_2    122.40000    148.65000    113.81900
phon_R01_S01_3    116.68200    131.11100    111.55500

I can read float numbers from file. I am currently reading each line from file but after that I am failing to extract/save/print both string and float numbers from line separately.

Edit1: For clarification to @zipa: I have tried below part to extract floats:

import numpy as np
from pprint import pprint
li = []

for line in open("a.txt"):
    nums = line.split() # split the line into a list of strings by whitespace
    nums = map(float, nums) # turn each string into a float

    pprint(nums)
    #li.extend(nums) 
    print line

pprint(li)

I haven't done any part to extract string. I couldn't find any. Above code gives this obvious below error.

nums = map(float, nums) # turn each string into a float
ValueError: could not convert string to float: phon_R01_S01_1
2
  • Can you show what you tried? Commented Apr 11, 2017 at 11:56
  • @zipa I have edited the question. Commented Apr 11, 2017 at 12:03

1 Answer 1

1

This could solve your issue:

nums = [nums[0]] + map(float, nums[1:])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I have got the main idea to extract those.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.