0

Ok here we go, i've been looking at this all day and i'm going crazy, i thought i'd done the hard bit but now i'm stuck. I'm making a highscores list for a game and i've already created a binary file that store the scores and names in order. Now i have to do the same thing but store the scores and names in a text file.

This is the binary file part but i have no idea where to start with using a text file.

def newbinfile():

    if not os.path.exists('tops.dat'):
        hs_data = []
        make_file = open('tops.dat', 'wb')
        pickle.dump(hs_data, make_file)
        make_file.close     
    else:
        None


def highscore(score, name):

    entry = (score, name)

    hs_data = open('tops.dat', 'rb')
    highsc = pickle.load(hs_data)
    hs_data.close()

    hs_data = open('tops.dat', 'wb+')
    highsc.append(entry)
    highsc.sort(reverse=True)
    highsc = highsc[:5]
    pickle.dump(highsc, hs_data)
    hs_data.close()

    return highsc

Any help on where to start with this would be appreciated. Thanks

4
  • what is the point of the else: None line? Commented Jun 24, 2013 at 17:47
  • also you forgot the parens after make_file.close () Commented Jun 24, 2013 at 17:49
  • I'm fairly new to this and the 'else: None' i put there because i thought it would throw up an error. I see i forgot the () but it didnt cause the the program to fail. Commented Jun 24, 2013 at 18:02
  • the else: None actually doesn't do anything, removing it will change nothing about the program. If you meeant to signal an error, you should raise an exception of some kind. I'm not sure what the error in this case would be though. Commented Jun 24, 2013 at 18:06

3 Answers 3

3

I think you should use the with keywords.

You'll find examples corresponding to what you want to do here.

with open('output.txt', 'w') as f:
    for l in ['Hi','there','!']:
        f.write(l + '\n')
Sign up to request clarification or add additional context in comments.

3 Comments

Ah ok i'll do a bit of reading, thanks for help. Sorry i can't green light all these solutions.
Not that I care about the green tick but with is the way to go.
So your with statement here writes hi - there - ! into output.txt? If this is the case can i use it to write from nested lists into the text file also?
2

Start here:

>>> mydata = ['Hello World!', 'Hello World 2!']
>>> myfile = open('testit.txt', 'w')
>>> for line in mydata:
...     myfile.write(line + '\n')
... 
>>> myfile.close()           # Do not forget to close

EDIT :

Once you are familiar with this, use the with keyword, which guaranties the closure when the file handler gets out of scope:

>>> with open('testit.txt', 'w') as myfile:
...     for line in mydata:
...         myfile.write(line + '\n')
...

2 Comments

I recommend using the with keyword instead of just opening the file. That ensures it will be closed properly without need a try-except block.
I agree, but form the pedagogic point of view, for a beginner, I find it good to start with things that are explicit... Then go into more advanced pythonic stuffs.
1

Python has built-in methods for writing to files that you can use to write to a text file.

writer = open("filename.txt", 'w+')
# w+ is the flag for overwriting if the file already exists
# a+ is the flag for appending if it already exists

t = (val1, val2) #a tuple of values you want to save

for elem in t:
    writer.write(str(elem) + ', ')
writer.write('\n') #the write function doesn't automatically put a new line at the end

writer.close()

1 Comment

So with this you can write information stored in tuples to a text file. Awesome! Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.