从txt文件中读取和写入数字

时间:2017-12-09 21:21:59

标签: python python-3.x int

每当我尝试将一个int变量写入txt文件时,它表示我无法将数字写入文本文件,代码:

f = open("money.txt", "w+")
#other code to roll the slot machine
money = money - 1`
f.truncate()
f.write(money)
f.close()

当我将money变量转换为字符串时,它只是在txt文件中说:100-1,就像你从100开始那样但是你 - 1因为你滚动了老虎机。

当我尝试读取该文本文件成为money变量时,它会变成一个字符串,所以我这样做:

f = open(int("money.txt", "w+"))
money = f.readlines()

但后来它说你不能把钱变成一个int。

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

你打开一个文件然后读作int而不是以int打开,也不是为了写,而是为了阅读......

open(int("money.txt", "w+"))

应该是

open("money.txt", "r")

然后阅读整理...

e.g。

NUMBER_FILE = "number.txt"


def writeInt(filename, integer):
    """Write a number to a file"""
    with open(filename, "w") as fo:
        fo.write("%d" % integer)


def readInt(filename):
    """read the contents of a file"""
    with open(filename, "r") as fi:
        return fi.read()


def main():
    writeInt(NUMBER_FILE, 42)
    print readInt(NUMBER_FILE)


if __name__ == '__main__':
    main()
相关问题