在python中覆盖文本文件中以字符串开头的文本行

qrjkbowd  于 2022-11-19  发布在  Python
关注(0)|答案(3)|浏览(131)

我有一个文本文件如下:
myfile.txt

[items]
colors = red, purple, orange, blue
[eat]
food = burgers, pizza, hotdogs 
[furry]
animals = birds, dogs, cats

我有一本字典:

my_dict = {'colors':'green, black','animals':'donkey, tigers'}

我想打开文件 myfile.txt,搜索文件中的键,并将行替换为my_dict的值,这样myfile. txt看起来应该是:
myfile.txt

[items]
colors = green, black
[eat]
food = burgers, pizza, hotdogs 
[furry]
animals = donkey, tigers

我试过做一些事情,比如:

def func(my_dict):
   # Read in the file
   with open('myfile.txt', 'r') as file :
       filedata = file.read()

       # Replace the target string
       filedata = filedata.replace('colors', my_dict)

   # Write the file out again
   with open('myfile.txt', 'w') as file:
       file.write(filedata)

问题是我得到的输出如下:

myfile.txt
green, black = red, purple, orange, blue
xcitsw88

xcitsw881#

新版本保留没有等号的文本

my_dict = {'colors': 'green, black', 'animals': 'donkey, tigers'}

def func(my_dict):
    # Get the file contents like you were already doing
    with open('myfile.txt', 'r') as file:
        filedata = file.read()

    # Now split the rows on newline
    lines = filedata.split('\n')
    # create a new list
    new_lines = []
    # Process each line of the file's contents
    for line in lines:
        # If it doesn't have an '=', just add it and continue iteration
        if "=" not in line: 
            new_lines.append(line)
            continue

        key, value = line.split("=")

        # if the key is in replacement dictionary, append a line with the new value
        if key.strip() in my_dict.keys():
            new_lines.append(f'{key.strip()} = {my_dict[key.strip()]}')
        # else just add the old line
        else:
            new_lines.append(line)

    with open('myfile.txt', 'w') as file:
        # join the new lines for the file with a newline character
        file.write('\n'.join(new_lines))

func(my_dict)

旧版本

# Get the file contents like you were already doing
with open('myfile.txt', 'r') as file:
    filedata = file.read()

# Now split the rows on newline
lines = filedata.split('\n')
# Create an empty dictionary
pairs = {}
# Process each line of the file's contents
for line in lines:
    # If it doesn't have an '=', skip the line
    if "=" not in line: continue
    key, value = line.split("=")
    # fill the dictionary with the keys and values in the file
    pairs[key.strip()] = value.strip()

my_dict = {'colors': 'green, black', 'animals': 'donkey, tigers'}

# replace the previous files values with any new values from the new dictionary
for k, v in my_dict.items():
    pairs[k] = v

# format the dictionary back into a line of text "colors = blue, black, etc."
new_lines = [f'{k} = {v}' for k, v in pairs.items()]

with open('myfile.txt', 'w') as file:
    # join the new lines for the file with a newline character
    file.write('\n'.join(new_lines))
bmp9r5qi

bmp9r5qi2#

你已经给出了一个函数,这个函数把my_dict当作一个字符串,但是你在replace方法中把它当作了一个字符串。你应该给出你是如何调用函数的。但是,这是解决方案。注解解释了发生了什么。我没有从文件中阅读,而是创建了一个和你的文件内容一样的字符串。你可以改变相关的部分。我们使用了split方法来把作为键和值对。

my_dict = {'colors':'green, black','animals':'donkey, tigers'}

def func(my_dict):
    filedata = """colors = red, purple, orange, blue\nfood = burgers, pizza, hotdogs \nanimals = birds, dogs, cats"""
    #get lines of line
    lines = filedata.split("\n")
    #this will store our final text
    fileDict = {}
    for line in lines:
        #get key from file/source
        key = line.split(" = ")[0]
        if(key in my_dict.keys()):
            #if key exist in your dict, change it with your my_dict value
            newValues = my_dict[key]
            fileDict[key] = newValues
        else:
            #if key not exist in your my_dict, use file/source values
            fileDict[key] = line.split(" =")[1]

    #stringify dictionary
    text = ""
    for key,value in fileDict.items():
        text += f"{key} = {value}\n" 

    #write to file
    with open('myfile.txt', 'w') as file:
       file.write(filedata)  

func(my_dict)
agyaoht7

agyaoht73#

您需要在等号上拆分句子(行),并替换等号的第二部分。

with open("myfile.txt") as file:
    for line in file.readlines():
        if "colors" in line:
            filedata = line.replace(line.split(" = ")[1], my_dict["colors"])

编写时,语法应该相同。

相关问题