首页 > 解决方案 > 如何在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

是 = 重复()

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

标签: pythondictionary

解决方案


您不能重写文件中的特定字节,您必须重写整个文件。

可能将文件读入字符串列表,处理该列表并将其写回文件将解决您的任务。


推荐阅读