简体   繁体   中英

How do you replace certain lines in a text file?

I'm creating a password generator, and I have a file with all the saved passwords, i want to rewrite certain lines of the code. Here is my code

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")

After this I want it to rewrite some specific lines. Is this possible?

use configparser , that will be easy to read and changes variable

https://docs.python.org/3/library/configparser.html

it's taken from thequick start config parser

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)

This will replace a line that starts with a keyword provided, hope it helps. Don't think there's a way to do it without reading the entire file.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM