繁体   English   中英

Python:尝试追加到文件,但未编写任何内容

[英]Python: Attempting to append to file but nothing is being written

这部分代码应将输入和另一个变量(分数)写入文本文件。 该程序要求输入(因此if语句肯定可以正常工作),并且运行时没有错误,但文本文件为空。 奇怪的是,将此代码复制到一个空的python文件中并运行它不会出错。 这是怎么回事

if Score > int(HighScores[1]):
    print("You beat the record with " + str(Score) + " points!")
    Name = input("What is your name?")
    BestOf = open("High Scores.txt", "w").close()
    BestOf = open("High Scores.txt", "a")
    BestOf.write(Name + "\n")
    BestOf.write(str(Score))

追加后我没有关闭文件。

BestOf.close()

修复

尝试以“ w +”模式打开文件。 如果文件不存在,将创建该文件。 您还可以使用“ os”模块检查文件是否退出。

import os;
if Score > int(HighScores[1]):
    print("You beat the record with " + str(Score) + " points!")
    name = input("What is your name?")
    if os.path.isfile("Scores.txt"):
        fh = open("Scores.txt", "a")
    else:
        fh = open("Scores.txt", "w+")
    fh.write(name + "\n")
    fh.write(str(Score))
    fh.close()

暂无
暂无

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

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