如何在python中编辑文本字段中的数字?

2024-03-29 02:01:13 发布

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

所以我试着浏览一个文本文件,把它放到字典里,然后检查是否已经有一个字符串在里面了。如果是,我想把“1”改成“2”。当前,如果字符串已经在文本文件中,它将只生成一个新行,但带有“2”。有没有办法编辑文本文件,使数字可以留在同一个地方,但被取代?你知道吗

class Isduplicate:
dicto = {}

def read(self):
    f = open(r'C:\Users\jacka\OneDrive\Documents\outputs.txt', "r")

    for line in f:
        k, v = line.strip().split(':')
        self.dicto[k.strip()] = int(v.strip())

    return self.dicto

Is=Isduplicate()

while counter < 50:
   e = str(elem[counter].get_attribute("href"))
   e = e.replace("https://www.reddit.com/r/", "")
   e = e[:-1]

   if e in Is.read():
       Is.dicto[e] += 1
   else:
       Is.dicto[e] = 1

   text_file.write(e + ":" + str(Is.dicto[e]) + '\n')




   print(e)
   counter = counter +2

Tags: 字符串inself编辑read字典isline