python - 如何在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
解决方案
您不能重写文件中的特定字节,您必须重写整个文件。
可能将文件读入字符串列表,处理该列表并将其写回文件将解决您的任务。
推荐阅读
- python - 从索引中减少 Pandas DataFrame 中的行
- c# - 将对象列表分隔为仅包含唯一项的多个列表
- ios - 如何使用 HKHeartbeatSeriesSample 检索一段时间内的心跳?
- python - 无法将对象附加到列表
- python - 如果链接在href标签(gspread)内,如何从Google电子表格中的单元格读取链接
- c++ - 以下哪个答案相当于 Ubuntu 14.04 LTS 上的 O_RDWR?
- php - 在古腾堡中显示 wordpress 画廊图像 src
- reactjs - 登录 Strapi 管理面板时出现 Error400
- css - z-index 没有按预期工作,父组件的 box-shadow 应该略高于 span
- python - 如何摆脱 3rd collections.abc DeprecationWarning