用字典中的值修改文本文件



我有一个如下的文本文件:

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

我试过这样做:

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

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

myfile.txt
colors = red, purple, orange, blue
food = burgers, pizza, hotdogs 
animals = birds, dogs, cats

括号中的所有文本都被丢弃。我需要保留标题[items], [eat]等。

不需要从文件创建字典。只需替换与新字典中的内容匹配的行。

my_dict = {'colors': 'green, black', 'animals': 'donkey, tigers'}
with open('myfile.txt', 'r') as file:
filedata = file.read()
# Now split the rows on newline
lines = filedata.split('n')
# Process each line of the file's contents
for i, line in enumerate(lines):
# If it doesn't have an '=', skip the line
if "=" not in line: continue
key, value = line.split("=")
key = key.strip()
if key in my_dict:
lines[i] = f'{key} = {my_dict[key]}'
with open('myfile.txt', 'w') as file:
# join the new lines for the file with a newline character
file.write('n'.join(lines)) 

最新更新