简体   繁体   English

将用户输入写入python中的文本文件

[英]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 谢谢

I think you should use the with keywords. 我认为您应该使用with关键字。

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

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关键字,该关键字可在文件处理程序超出范围时保证关闭:

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

Python has built-in methods for writing to files that you can use to write to a text file. Python具有用于写入文件的内置方法,可用于写入文本文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM