1

This is simple but I just cant seem to get it right.

I have a text file containing numbers in the form

0 1 2
3 43 
5 6 7 8

and such.

I want to read these numbers and store it in a list such that each number is an element of a list. If i read the entire file as a string, how can I split the string to get these elements separated?

Thanks.

3
  • Do you want to store the numbers as ints or strings? Commented Dec 22, 2012 at 7:37
  • I do not think regex tag applies here... Commented Dec 22, 2012 at 7:39
  • The stupid tagging has already been fixed. Commented Dec 22, 2012 at 7:43

3 Answers 3

3

You can iterate over the file object as if it were a list of lines:

with open('file.txt', 'r') as handle:
    numbers = [map(int, line.split()) for line in handle]

A slightly simpler example:

with open('file.txt', 'r') as handle:
    for line in handle:
        print line
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. never seen that syntax before!
1

First, open the file. Then iterate over the file object to get each of its lines and call split() on the the line to get a list of strings. Then convert each string in the list to a number:

f = open("somefile.txt")

nums = []
strs = []

for line in f:
    strs = line.split() #get an array of whitespace-separated substrings 
    for num in strs:
         try:
             nums.append(int(num)) #convert each substring to a number and append
         except ValueError: #the string cannot be parsed to a number
             pass

nums now contains all of the numbers in the file.

Comments

0

how can I split the string to get these elements separated

string.split()

Comments

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.