写入文件python-换行符问题(\n)

写入文件python-换行符问题(\n),python,windows,Python,Windows,我有一个问题,函数只是覆盖了.txt文件中已经存在的行。该函数应该在游戏退出时向文件写入高分(我根据youtube教程制作了一个snake游戏)。我不太明白为什么它不能在一条新的线路上启动,谁能解释一下它背后的逻辑,以及我如何修复它?我在某个地方读到,我应该键入“rb”之类的字,而不是f.open()中的“w”。因为我对“写文件”这件事有点陌生,我觉得很难 此外,我还想将文件中的高分从最高到最低排序(换句话说,将finalScore从最高到最低排序)。我不知道我应该如何继续和代码,所以我会感谢一

我有一个问题,函数只是覆盖了.txt文件中已经存在的行。该函数应该在游戏退出时向文件写入高分(我根据youtube教程制作了一个snake游戏)。我不太明白为什么它不能在一条新的线路上启动,谁能解释一下它背后的逻辑,以及我如何修复它?我在某个地方读到,我应该键入“rb”之类的字,而不是f.open()中的“w”。因为我对“写文件”这件事有点陌生,我觉得很难

此外,我还想将文件中的高分从最高到最低排序(换句话说,将finalScore从最高到最低排序)。我不知道我应该如何继续和代码,所以我会感谢一些帮助。你看,我想把当前的高分打印到控制台上(以便制作记分板)

代码如下:

import random
import time

name = "Andreas"
finalScore = random.randint(1,10)

def scoreToFile(finalScore):
    #Has to be generated here, since we need the exact current time
    currentTime = time.strftime("%c")
    print("Sucsessfully logged score (finalScore) to highscores.txt")
    f = open("highscores.txt", "w")
    #fileOutput = [(currentTime, ":", name, "-", finalScore)]
    fileOutput = [(finalScore, "-", name, currentTime)]
    for t in fileOutput:
        line = ' '.join(str(x) for x in t)
        f.write(line + "\n")
    f.close()

scoreToFile(finalScore)
无论如何,圣诞快乐,我的巨蟒怪人们D

1)一个选项是以附加模式打开文件。 替换:

与:

2) 另一个选择是替换此块

f = open("highscores.txt", "w")
#fileOutput = [(currentTime, ":", name, "-", finalScore)]
fileOutput = [(finalScore, "-", name, currentTime)]
for t in fileOutput:
    line = ' '.join(str(x) for x in t)
    myfile.write(line + "\n")
f.close()
并且使用一个有风格的

with open("highscores.txt", "a") as myfile:
    #fileOutput = [(currentTime, ":", name, "-", finalScore)]
    fileOutput = [(finalScore, "-", name, currentTime)]
    for t in fileOutput:
        line = ' '.join(str(x) for x in t)
        myfile.write(line + "\n")
我更喜欢第二种样式,因为它更安全、更干净。

1)一个选项是以附加模式打开文件。 替换:

与:

2) 另一个选择是替换此块

f = open("highscores.txt", "w")
#fileOutput = [(currentTime, ":", name, "-", finalScore)]
fileOutput = [(finalScore, "-", name, currentTime)]
for t in fileOutput:
    line = ' '.join(str(x) for x in t)
    myfile.write(line + "\n")
f.close()
并且使用一个有风格的

with open("highscores.txt", "a") as myfile:
    #fileOutput = [(currentTime, ":", name, "-", finalScore)]
    fileOutput = [(finalScore, "-", name, currentTime)]
    for t in fileOutput:
        line = ' '.join(str(x) for x in t)
        myfile.write(line + "\n")

我更喜欢第二种样式,因为它更安全、更干净。

模式
w
覆盖现有文件;模式“a”在其后面追加。此外,处理文件的最佳方式通常是使用
with
语句,这可以确保代表您关闭文件;因此:

fileOutput = [(finalScore, "-", name, currentTime)]
with open("highscores.txt", "a") as f:
    for t in fileOutput:
        line = ' '.join(str(x) for x in t)
        f.write(line + "\n")
对于排序,您需要能够从一行中提取最终分数作为数字:

def minus_score(line):
    return -int(line.split()[0])
然后,将按照以下方式完成全部工作:

def sorted_by_score():
    with open("highscores.txt", "r") as f:
        result = list(f)
    return sorted(result, key=minus_score)
这将为您提供一个按分数升序排序的列表行(后者的原因是
score
对数字求反,尽管您也可以选择让它只返回数字并反转排序),以便您循环并进一步处理

补充:根据OP的要求,这里是整个程序的运行方式(假设存在一个函数,该函数要么玩游戏并返回玩家姓名和最终分数,要么在不再玩游戏且程序必须退出时返回
None


模式
w
覆盖现有文件;模式“a”在其后面追加。此外,处理文件的最佳方式通常是使用
with
语句,这可以确保代表您关闭文件;因此:

fileOutput = [(finalScore, "-", name, currentTime)]
with open("highscores.txt", "a") as f:
    for t in fileOutput:
        line = ' '.join(str(x) for x in t)
        f.write(line + "\n")
对于排序,您需要能够从一行中提取最终分数作为数字:

def minus_score(line):
    return -int(line.split()[0])
然后,将按照以下方式完成全部工作:

def sorted_by_score():
    with open("highscores.txt", "r") as f:
        result = list(f)
    return sorted(result, key=minus_score)
这将为您提供一个按分数升序排序的列表行(后者的原因是
score
对数字求反,尽管您也可以选择让它只返回数字并反转排序),以便您循环并进一步处理

补充:根据OP的要求,这里是整个程序的运行方式(假设存在一个函数,该函数要么玩游戏并返回玩家姓名和最终分数,要么在不再玩游戏且程序必须退出时返回
None


正如其他人提到的,问题是您没有以追加模式打开文件,因此每次都会覆盖文件,而不是添加到文件中

但是,如果还希望对文件中的数据进行排序,则每次都要覆盖该数据,因为添加内容可能会改变其内容顺序。要做到这一点,首先需要读取其中的内容,更新数据,然后再将其写回

这是函数的一个修改版本,可以实现这一点。我还将文件中的数据存储方式更改为所谓的格式,因为Python包含了amodule,这使得读取、写入和处理此类文件非常容易

import csv
import random
import time

highscores_filename = "highscores.txt"
HighScoresFirst = True  # Determines sort order of data in file

def scoreToFile(name, finalScore):
    currentTime = time.strftime("%c")
    # Try reading scores from existing file.
    try:
        with open(highscores_filename, "r", newline='') as csvfile:
            highscores = [row for row in csv.reader(csvfile, delimiter='-')]
    except FileNotFoundError:
        highscores = []
    # Add this score to the end of the list.
    highscores.append([str(finalScore), name, currentTime])
    # Sort updated list by numeric score.
    highscores.sort(key=lambda item: int(item[0]), reverse=HighScoresFirst)
    # Create/rewrite highscores file from highscores list.
    with open(highscores_filename, "w", newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter='-')
        writer.writerows(highscores)
    print("successfully logged score (finalScore) to highscores.txt")

# Simulate using the function several times.
name = "Name"
for i in range(1, 4):
    finalScore = random.randint(1,10)
    scoreToFile(name + str(i), finalScore)
    time.sleep(random.randint(1,3))  # Pause so time values will vary.

正如其他人提到的,问题是您没有以追加模式打开文件,因此每次都会覆盖文件,而不是添加到文件中

但是,如果还希望对文件中的数据进行排序,则每次都要覆盖该数据,因为添加内容可能会改变其内容顺序。要做到这一点,首先需要读取其中的内容,更新数据,然后再将其写回

这是函数的一个修改版本,可以实现这一点。我还将文件中的数据存储方式更改为所谓的格式,因为Python包含了amodule,这使得读取、写入和处理此类文件非常容易

import csv
import random
import time

highscores_filename = "highscores.txt"
HighScoresFirst = True  # Determines sort order of data in file

def scoreToFile(name, finalScore):
    currentTime = time.strftime("%c")
    # Try reading scores from existing file.
    try:
        with open(highscores_filename, "r", newline='') as csvfile:
            highscores = [row for row in csv.reader(csvfile, delimiter='-')]
    except FileNotFoundError:
        highscores = []
    # Add this score to the end of the list.
    highscores.append([str(finalScore), name, currentTime])
    # Sort updated list by numeric score.
    highscores.sort(key=lambda item: int(item[0]), reverse=HighScoresFirst)
    # Create/rewrite highscores file from highscores list.
    with open(highscores_filename, "w", newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter='-')
        writer.writerows(highscores)
    print("successfully logged score (finalScore) to highscores.txt")

# Simulate using the function several times.
name = "Name"
for i in range(1, 4):
    finalScore = random.randint(1,10)
    scoreToFile(name + str(i), finalScore)
    time.sleep(random.randint(1,3))  # Pause so time values will vary.

Do
f=open(“highscores.txt”,“a”)
。注意.Do
f=open(“highscores.txt”,“a”)
。注意这个,太好了!谢谢现在我只需要弄清楚如何对分数进行排序:太好了!谢谢现在我只需要弄清楚如何对分数进行排序:我不太明白。。。我应该在代码中的何处调用函数,并且
中的
是否与scoreToFile函数中的
相同?你能把全部代码粘贴在这里吗?谢谢你的详细回答,无论如何!:)至于什么时候你应该调用按分数排序的
:你只说了“我想对高分进行排序”-所以当你调用它时,正好是你想对“高分”进行排序的时候(循环,在控制台上打印一些,或者其他什么)。你从来不说什么时候要对它们进行排序,我也看不懂你的心思,所以我不知道什么时候调用“按分数排序”
——两个“when”是相同的——是在
scoreToFile
之后,还是在最后,或者在任何时候。你从不直接调用
减分
;内置的
sorted
调用它来生成您想要的排序。哦,还有,澄清一下:我不能“在这里粘贴整个代码”,因为您的规范不清楚什么时候应该做什么(您希望在添加每个新分数后“打印到控制台”,还是在整个程序完成时,或者在什么时候