伙计们,我正在尝试制作一个密码生成器,但我遇到了这个问题:
首先,我用于测试的代码:
idTest= "TEST"
passwrd= str(random.randint(11, 99))
if not os.path.exists('Senhas.txt'):
txtFileW = open('Senhas.txt', 'w')
txtFileW.writelines(f'{idTest}: {passwrd}n')
txtFileW.close()
else:
txtFileA = open('Senhas.txt', 'a')
txtFileA.write(f'{idTest}: {passwrd}n')
txtFileA.close()
print(f'{idTest}: {passwrd}')
好吧,我期待的是这样的东西:
else:
with open('Senhas.txt', 'r+') as opened:
opened.read()
for lines in opened:
if something == idTest:
lines.replace(f'{something}', f'{idTest}')
else:
break
txtFileA = open('Senhas.txt', 'a')
txtFileA.write(f'{idTest}: {passwrd}n')
txtFileA.close()
print(f'{idTest}: {passwrd}')
我已经搜索过了,但我所找到的都是将它分为两个文件的方法(对于我的项目来说,它不匹配(或用";静态";字符串,这对我来说也不匹配。
您可以使用fileinput
模块就地更新文件。
import fileinput
with fileinput.input(files=('Senhas.txt'), inplace=True) as f:
for line in f:
if (line.startswith(idTest+':'):
print(f'{idTest}: {passwrd}')
else:
print(line)