Looks you have only one number per line so you do not need to loop line by line. I am not going ot show directly how to make them int egers instead of str ings, but this gets you the strings:
number_strings = list(f)
pyTony
pyMod
6,300 posts since Apr 2010
Reputation Points: 879
Solved Threads: 986
Skill Endorsements: 26
So, what will this do?
with open('numbers.txt') as f:
for line in f:
print(line, type(line))
Ene Uran
Posting Virtuoso
1,830 posts since Aug 2005
Reputation Points: 676
Solved Threads: 255
Skill Endorsements: 7
So, you have a filename called 'numbers.txt' which looks kinda like this:
'''
1
2
3
4
5
6
7
8
'''
You could make all that a list of strings, than work with them:
l = []
with open('numbers.txt') as f:
l = list(f)
print l
Or, you could parse the entire file, line by line, and append your items to the list, also, converting them to int.
Useful links:
List operations
The 'with' statement
Good luck.
Lucaci Andrew
Practically a Master Poster
649 posts since Jan 2012
Reputation Points: 91
Solved Threads: 91
Skill Endorsements: 11
Just another way ...
with open('numbers.txt') as f:
raw_list = f.readlines()
print raw_list
mylist = [eval(item) for item in raw_list]
print mylist
'''
['1\n', '2\n', '3\n', '4\n', '5\n', '6\n', '7\n', '8\n', '9\n', '10\n']
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
'''
vegaseat
DaniWeb's Hypocrite
6,464 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,608
Skill Endorsements: 34
Or you could use the old fashion append style.
l = []
with open('numbers.txt') as f:
for i in f: l.append(int(i))
print l
'''
[1, 2, 3, 4, 5, 6, 7, 8]
'''
Lucaci Andrew
Practically a Master Poster
649 posts since Jan 2012
Reputation Points: 91
Solved Threads: 91
Skill Endorsements: 11
Question Answered as of 2 Months Ago by
Lucaci Andrew,
vegaseat,
Ene Uran
and 3 others