0

I am very new at programming. I have the following problem.

I want to take some floats from a .txt file, and add them to a Python list as strings, with a comma between them, like this:

.TXT:
194220.00   38.4397984  S   061.1720742 W   0.035
194315.00   38.4398243  S   061.1721378 W   0.036

Python:

myList = ('38.4397984,061.1720742','38.4398243,061.1721378')

Does anybody know how to do this? Thank you!

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
andresmechali
  • 705
  • 2
  • 7
  • 18
  • 1
    It generally helps you to get better answers if you are able to show what you've tried to this point. A minor nitpick: `myList` is being declared as a tuple. Have a look at the `csv` module for some ideas of how to proceed. – mechanical_meat Jul 04 '12 at 22:44

2 Answers2

2

There are three key pieces you'll need to do this. You'll need to know how to open files, you'll need to know how to iterate through the lines with the file open, and you'll need to know how to split the list.

Once you know all these things, it's as simple as concatenating the pieces you want and adding them to your list.

my_list = []
with open('path/to/my/file.txt') as f:
    for line in f:
        words = line.split()
        my_list.append(words[1] + words[3])
print mylist
Community
  • 1
  • 1
Wilduck
  • 13,822
  • 10
  • 58
  • 90
0

Python has a method open(fileName, mode) that returns a file object. fileName is a string with the name of the file. mode is another a string that states how will the file used. Ex 'r' for reading and 'w' for writing.

f = open(file.txt, 'r')

This will create file object in the variable f. f has now different methods you can use to read the data in the file. The most common is f.read(size) where size is optional

text = f.read()

Will save the data in the variable text.

Now you want to split the string. String is an object and has a method called split() that creates a list of words from a string separated by white space.

myList = text.split()

In your code you gave us a tuple, which from the variable name i am not sure it was what you were looking for. Make sure to read the difference between a tuple and a list. The procedure to find a tuple is a bit different.

danielz
  • 1,767
  • 14
  • 20