该函数从 users.txt 文件中读取用户的登录名(那里总是只有一个登录名),然后查找相同的 inprogress.txt,如果找到,则需要将登录名后面的行替换为再一个,从 1 到 2,从 2 等。.d。是班级编号。如果是第一次输入登录名,那么只需将其写入progress后跟1。问题是我不明白如何从文件中获取带有数字的这一行,将其转换为int,加1,然后把它写到同一个地方。或许答案是显而易见的,但我对 Python 才熟悉几天,还是不太了解。提前致谢
with open('users.txt', 'r') as f:
line = f.readline()
f.close()
with open('progress.txt', 'r') as k:
while True:
global uroka_in
lines = k.readline()
if line == lines.rstrip():
uroka_in = int(k.readline().rstrip())
urokb_in = uroka_in + 1
uroka_str = str(uroka_in)
urokb_str = str(urokb_in)
lines.replace(uroka_str, urokb_str)
k.close()
break
if not lines:
k.close()
global urokb_in
urokb_in = 1
with open('progress.txt', 'a') as j:
j.write(line)
j.write('\n')
j.write(str(urokb_in))
j.write('\n')
j.close()
break
示例 progress.txt 文件:
username1
1
username2
1
username3
1
编辑:
def user():
with open('users.txt') as k:
user = k.readline()
k.close()
def increment_counter(user, 'progress.txt'):
with open('progress.txt', 'r') as f:
data = yaml.safe_load(f.read())
data[user] += 1
with open('progress.txt', 'w') as f:
yaml.dump(data, f, indent=2, default_flow_style=False)
试试这样:
使用示例:
progress.yml函数调用之前的示例 YAML 文件 ( ):"progress.yml"通话后内容increment_counter('username3', r'/path/to/progress.yml'):纯文本文件的功能(如问题所示)
使用示例:
PS 我推荐使用 YAML 来存储用户数据
例如'progress.txt'
空的“progress.txt”最初应该包含一行:
{}另一种选择,正如问题作者想要的那样:
例如'progress.txt'