-3

I'm having the user input a file to open which contains numbers. I want the output to be the number of elements in the file. I put..

file=open(input("Please enter the name of the file you wish to open:" ))#, "r")
A= file.readline()

print (A)

n=len(A)
print (n)

I am very new to this. The file I am testing it with has 9 numbers (2 of which are negative). The length comes out to 21. How can I change this to get the number of elements?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

5

If the numbers are all on that line, use split to separate the string into individual numbers:

# List of strings: ['1', '-3', '10', ...]
numbers = A.split()

print len(numbers)

You may also want to convert those numbers from string form to int form:

# List of numbers: [1, -3, 10, ...]
numbers = [int(n) for n in A.split()]
John Kugelman
  • 349,597
  • 67
  • 533
  • 578