1

I have made this small piece of code that collects a name and a highscore and puts it into a list into a file. Here is my code:

def main():
    pass
    fileobj = open('c:\\newfile.txt', 'w')
    count = 0
    player_names = []
    high_scores = []
    while count < 5:
        player_name = input('Name: ')
        high_score =  input('High Score: ')
        player_names.append(player_name)
        high_scores.append(high_score)
        fileobj.write(player_name + '\n')
        fileobj.write(high_score + '\n')
        count = count + 1
    fileobj.close()

What I am trying to do is create another script that will read that file and print the list and sort it according to the High score values, I have been reading for like an hour or two on how to do it but cant just get the hang of it. This is what my other script looks like so far:

def main():
    pass
    f = open('c:\\newfile.txt', 'r')
    print f
    f.readline()

I get an error on the print f line, but when I take that out the script runs but nothing is displayed.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
yassterday
  • 11
  • 1
  • 1
    Pro tip: you can safely remove the `pass` statements when there is other code in the compound statement (e.g. the function *does* something). – Martijn Pieters Oct 06 '14 at 09:52
  • You are doing nothing with the `f.readline()` call; use `line = f.readline()`, then `print(line)` to see that first line read. – Martijn Pieters Oct 06 '14 at 09:55
  • oh yeahp got it thanks ! the pass is there just cause it was in the scripter application im using, what if i wanted to sort that list by the high score value? how would i implement that? – yassterday Oct 06 '14 at 10:14

2 Answers2

0

You are getting error because print() is a function in python3.

print(f)

is the correct way. Also i did not get the significance of pass statements.If you want to print the contents of file then use:

print(f.read()).

Nothing is getting displayed on screen after removing print f because f.readline() does not print anything it just reads the file from current file pointer to first occurance of \n and returns it as string. You can assign f.readline() to some variable like line = f.readline() or you can directly display it on stdout like print(f.readline())

Ashwani
  • 1,938
  • 11
  • 15
0

Try replacing your last two line with:

print (f.read())

Alternatively if you want to do something to each line you can try:

def main():
    for line in open('c:\\newfile.txt', 'r'): 
        #do_something_to_line
        print line

It looks like you are trying to print out the file handle rather than the data in the file at the moment.

Tommy
  • 622
  • 5
  • 8