Home > Software engineering >  How do you replace certain lines in a text file?
How do you replace certain lines in a text file?

Time:04-26

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?

CodePudding user response:

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

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

it's taken from the quick 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)

CodePudding user response:

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)
  • Related