jimmy Light
jimmy Light

Reputation: 107

Writing user input to a text file in python

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

Upvotes: 0

Views: 511

Answers (3)

Gauthier Boaglio
Gauthier Boaglio

Reputation: 10242

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')
...

Upvotes: 2

SylvainD
SylvainD

Reputation: 1763

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')

Upvotes: 3

xgord
xgord

Reputation: 4776

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()

Upvotes: 1

Related Questions