1

I am having issues trying to square numbers in a text file.

The text file I have has the following:

2 8 4 3

7 14 12

9

This is my code so far:

def squares(nums):
    answer = []
    for i in nums:
        answer.append(i*i)
    return answer

def main():
    fname = input("What is the filename? ")
    nums = open(fname, 'r')

    n = []
    for i in nums.readlines:
        n.append(i[:-1])
    j = squares(n)

    print(j)
main()

I don't know what the issue is, I've tried multiple things and can't figure it out. Can someone please help/guide me?

Thank you...

Joseph Dunbar
  • 41
  • 2
  • 4
  • possible duplicate of [How to read numbers from file in Python?](http://stackoverflow.com/questions/6583573/how-to-read-numbers-from-file-in-python) – en_Knight Mar 04 '15 at 03:22
  • Take a look here: http://stackoverflow.com/questions/6583573/how-to-read-numbers-from-file-in-python – en_Knight Mar 04 '15 at 03:22
  • I can't map it out to what I'm doing here, can you explain what I can do if you know how to get this program to work? – Joseph Dunbar Mar 04 '15 at 03:26
  • 1
    Does it even comiple? This `for i in nums.readlines` should be `for i in nums.readlines()`. – Marcin Mar 04 '15 at 03:42

1 Answers1

1

I made minimal changes to your code to make it actually work:

def squares(nums):
    answer = []
    for i in nums:
        answer.append(int(i)*int(i)) #<-- here you need integers or floats, not strings
    return answer

def main():
    #fname = input("What is the filename? ")
    nums = open('test.txt', 'r')

    n = []
    for i in nums: n += i.split() #<-- here you need to split line to get individual numbers

    nums.close() #<--you forget to close file after you are done reading from it.

    j = squares(n)

    print(j)

main()

The result is:

[4, 64, 16, 9, 49, 196, 144, 81]
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • I completely forgot that content in nums was still considered as strings and not ints (forgot the conversion). I have a question though, is it possible to use split() in the same line as : for i in nums.readlines(): ? Thank you so much for your help.. I will wait for your response. – Joseph Dunbar Mar 04 '15 at 03:53
  • No worries, yes you can: you can just write `for i in nums: n += i.split()`. Check edited answer. You could also use list comprehension, but it would create list of lists, so you would need to change squares. You dont have to worry about lists of lists if you have for like now, due using '+=' , which joints the sublists into one list. – Marcin Mar 04 '15 at 04:01