johnny
johnny

Reputation: 171

Adding list's elements after reading it from a file in Python

What i am trying to do is read elements from a file and add each line to print its output now the problem is i have tried a number of ways but i am unsuccessful for example if i want to access a certain number

with open('test.txt', 'r') as f:
    for line in f:
         for s in line.split(' '):
             num = int(s)
             print(num[1])

TypeError: 'int' object is not subscriptable

I tried another way to read each line store it in a list and then converting it into an int to use them later

with open('test.txt', 'r') as f:
    filer = f.readlines()
    filer = map(int, filer)
    print(filer[1])

but it still gives me an error

TypeError: 'map' object is not subscriptable

I am a beginner at python

Upvotes: 0

Views: 129

Answers (3)

user2555451
user2555451

Reputation:

In Python 3.x, map returns a map object, which does not support indexing.

To get what you want, place that object in list:

with open('test.txt', 'r') as f:
    filer = f.readlines()
    filer = list(map(int, filer))
    print(filer[1])

Or, you can use a list comprehension (which is often preferred):

with open('test.txt', 'r') as f:
    filer = f.readlines()
    filer = [int(x) for x in filer]
    print(filer[1])

Also, I just wanted to add that open defaults to read-mode. So, you can actually just do this:

with open('test.txt') as f:

However, some people like to explicitly put the 'r', so I'll leave that choice to you.

Upvotes: 4

wnnmaw
wnnmaw

Reputation: 5534

It seems that you're saving your number as a single number, you want to use a list. Try this

with open('test.txt', 'r') as f:
    numList = []
    for line in f:
         for s in line.split(' '):
             numList.append(int(s))       
             print numList[-1]

Upvotes: 1

quazzieclodo
quazzieclodo

Reputation: 831

Change print(num[1]) to print(num) if you want to just access one number at a time.

Upvotes: 0

Related Questions