# # This program opens a file (the file name is supplied by the user) with numbers. # Extracts them and stores them in a list. # This program understands lines on numbers separated by space as well as number-per-line # e.g. # 1 21 32 12 # 9 0 -9 23 1 # OR # 1 # 21 # 32 ... import string def main(): print "Hello!" print "This program opens a file with numbers, extracts all the numbers and stores them in a list." print "The file name is supplied by the user." fname=raw_input("Please, input the name of the file with numbers:") inp=open(fname,'r') # loop in the numbers of lines in a file k=1 numbers=[0] for line in inp: print "Next line from the file: %s" % line # displays the line taken from the input file #line_s=inp.readline() # reads a line from the input file # split the string into a list of numbers using " " as a dilimeter, assigns to numbers_in_line numbers_in_line=string.split(line," ") n=len(numbers_in_line) # finds the number of elements in the numbers_in_line list # runs through all the elements of numbers_in_line list and appends them to the list 'numbers', # the list of all numbers in the file # if a line ends with \n then this newline character is removed for i in range(n): m=len(numbers_in_line[i]) # finds the number of digits (including newline character) # in the the elemtns of the numbers_in_list list (not an elegant solution) # this is neened for the check for newline character # if we reached the last element in the list numbers_in_line, and the last "digit" is # newline character then we cut it off the number # this approach covers the case when the last line of numbers in the file doesn't end with \n if i==n-1 and numbers_in_line[i][m-1] == "": #m=len(numbers_in_line[i]) numbers.append(eval(numbers_in_line[i][:m-1])) else: #numbers[k]=eval(numbers_in_line[i]) numbers.append(eval(numbers_in_line[i])) k=k+1; print "The numbers extracted from the file %s are:" % fname for i in range(k): print numbers[i] inp.close() main()