在python中使变量的行为类似于数字

2024-04-20 03:46:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在想,在python中,我怎么能让变量,比如一个单词,像一个数字一样,来创建一个点的系统,并将其写入我的计算机上的一个文本文件中

def pointsystem():
import easygui
points = open ('totalpoints.txt', 'r')
readpts = points.readline()
points.close
pointsinput = easygui.enterbox("enter paretal password")
if pointsinput == 'testpass':
    pointsadd = easygui.enterbox("enter points")
    pointsedit = open ('totalpoints.txt', 'a')
    pointsedit.write(readpts + pointsadd)
    pointsedit.close()

Tags: txtclose系统数字open单词pointsenter
1条回答
网友
1楼 · 发布于 2024-04-20 03:46:26

我认为readpts = int(readpts)pointsadd = int(pointsadd)可以实现这个技巧,将这些字符串转换成数字。然后在该写的时候用str(readpts + pointsadd)把它们改回来。你知道吗

基于注释编辑:实际上,您不能将数字作为整数类型存储在文件中(或者,如果可以的话,那就太麻烦了)。如果要用全新的数字替换文件中的数字,而不是不断地添加新的数字,请使用pointsedit = open ('totalpoints.txt', 'w')而不是pointsedit = open ('totalpoints.txt', 'a')。这将删除文件的原始内容并用新内容(新点数)替换它,而不只是添加越来越多的数字。但它必须作为字符串读入,然后作为字符串写出。这真的容易多了。你知道吗

def pointsystem():
  import easygui
  points = open ('totalpoints.txt', 'r')
  readpts = points.readline()
  points.close()
  readpts = int(readpts)
  pointsinput = easygui.enterbox("enter paretal password")
  if pointsinput == 'testpass':
    pointsadd = easygui.enterbox("enter points")
    pointsadd = int(pointsadd)
    pointsedit = open ('totalpoints.txt', 'w')
    pointsedit.write(str(readpts + pointsadd))
    pointsedit.close()

相关问题 更多 >