所以我试着浏览一个文本文件,把它放到字典里,然后检查是否已经有一个字符串在里面了。如果是,我想把“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
你不能重写文件中的某个字节,你必须重写整个文件。你知道吗
可能将文件读入字符串列表,处理该列表并将其写回文件将解决您的任务。你知道吗
相关问题 更多 >
编程相关推荐