簡體   English   中英

如何替換文本文件中的某些行?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM