[英]How do you replace certain lines in a text file?
我正在创建一个密码生成器,我有一个包含所有已保存密码的文件,我想重写某些代码行。 这是我的代码
reason = input("Why would you like to use this password?\n")
file = open("Password Saver.rtf", "a+")
file = open("Password Saver.rtf", "r+")
occ = 0
for line in file:
line = line.casefold()
words = line.split(" ")
for word in words:
if word == reason.casefold():
occ += 1
else:
continue
if occ > 1 or occ == 1:
Duplicate = input("You have already made a password with that reason, would you like to write it again?\n")
在此之后我希望它重写一些特定的行。 这可能吗?
使用configparser
,这将易于阅读和更改变量
https://docs.python.org/3/library/configparser.html
它取自快速启动配置解析器
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)
这将替换以提供的关键字开头的行,希望它有所帮助。 不要认为没有阅读整个文件就可以做到这一点。
file = 'pathtofile'
myKeyword = "Test3"
myNewLine = "The New line i want Test3 to be replaced with\n"
with open(file, "r+") as f:
allLines = f.readlines()
f.seek(0)
for line in allLines:
if not line.startswith(myKeyword):
f.write(line)
else:
f.write(myNewLine)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.