Venkata Venkata - 5 months ago 12
Python Question

how to loop and read from a file, a particular integers or strings using index in python?

I have currently in file one.txt:

99999 5286
88888 3478


I want to read only the numbers 99999, 88888 not the other numbers using a loop and write it to a file two.txt.

Answer

str.split will split a string on whitespace, eg, "a b c d" will become ["a", "b", "c", "d"]

The docs on split: https://docs.python.org/2/library/stdtypes.html#str.split

Solution to example:

with open('one.txt', 'r') as in_file, open('two.txt', 'w') as out_file:
    for in_string in in_file.readlines():
        out_file.write(in_string.split()[0])
        out_file.write('\n')