-3

I want to copy a string which is located at third place in a text file. Though I can count the character and copy the string based on their character index, I am afraid for some of the files this strings might have more or less number of characters. For example, in the below line I have third string as 239.943; for some other file it could also be 1022.345 or 98.234.

       1  51 239.943   .2081   .0137   .2016   .0017

Is there any way to identify and copy the third string i.e., 239.943 irrespective of its character length in python?

Jasmijn
  • 9,370
  • 2
  • 29
  • 43
dsbisht
  • 1,025
  • 4
  • 13
  • 24
  • Can you post your file and the expected output please? – Rakesh May 19 '18 at 09:03
  • I'm sorry, but there is no such thing to post. I am reading a text file, which has these numbers at second line. I am reading the line and want to copy second string. Likewise I will be copying second string iteratively for multiple files. – dsbisht May 19 '18 at 09:05

2 Answers2

1

Read line by line, split by spaces and read array[2] from the obtained array.

with open(filepath) as fp:  
    line = fp.readline()
    while line:
        arr = re.split(r'\s+', line)  
        print arr[2]
        line = fp.readline()
Georgy
  • 12,464
  • 7
  • 65
  • 73
Hemanth Gowda
  • 604
  • 4
  • 16
0

maybe your question is related to https://stackoverflow.com/a/2294502/7244300.

>>> s = "I have a cat"
>>> s.find("have")
2
lelouchkako
  • 123
  • 1
  • 7