【发布时间】:2021-04-09 00:22:31
【问题描述】:
我正在尝试使用 python 编程将不同的文本附加到特定范围内的多行末尾到文本文件中。
我的文本文件中的示例数据:
Cat 1: 27
Cat 2: 33
Cat 3: 15
Cat 4:
Cat 5:
Cat 6:
Cat 7: 89
我想将这组数据附加到带有文本“Cat 4”到“Cat 6”的行中:
44
22
64
我希望 python 程序的输出做到这一点:
Cat 1: 27
Cat 2: 33
Cat 3: 15
Cat 4: 44
Cat 5: 22
Cat 6: 64
Cat 7: 89
我在网上找到了这段代码,但它只是用新文本替换文本。它不附加文本,您必须使用单独的文件来实现它:
# create a dict of find keys and replace values
findlines = open('find.txt').read().split('\n')
replacelines = open('replace.txt').read().split('\n')
find_replace = dict(zip(findlines, replacelines))
with open('data.txt') as data:
with open('new_data.txt', 'w') as new_data:
for line in data:
for key in find_replace:
if key in line:
line = line.replace(key, find_replace[key])
new_data.write(line)
到目前为止,我不知道我需要什么代码,因为我是编程新手。我需要什么 python 代码来实现这一点,我怎样才能让它与一个文件而不是三个文件一起工作?另外,如何让程序一次读取一行,而不是一次将所有数据加载到内存中?我希望能够将这个程序用于大量这样的文本文件,并且我不希望它因为文本文件中的大量数据而冻结我的计算机。感谢您的帮助。
【问题讨论】: