搜索并使用python将文本复制粘贴到相应的文件

搜索并使用python将文本复制粘贴到相应的文件,python,python-3.x,Python,Python 3.x,假设我有一个包含本地商店产品价格的源文件 $ less SourceFile.txt # see this file using less function in terminal. Store Price Dollars >shop1 >price1 $5 >shop2 >price2 $3 而且,对于每个商店,都有一些称为子文件的营销数据,不幸的是,这些数据并不完整 $ less SubFile1.txt >owner TimmyCoLtd >sh

假设我有一个包含本地商店产品价格的源文件

$ less SourceFile.txt  # see this file using less function in terminal.
Store Price Dollars
>shop1 >price1 $5
>shop2 >price2 $3
而且,对于每个
商店
,都有一些称为
子文件
的营销数据,不幸的是,这些数据并不完整

$ less SubFile1.txt  
>owner
TimmyCoLtd
>shop1
grape 

$ less SubFile2.txt 
>shop2
potato
>salesman
John

$ less SubFile3.txt  # no discount information in Source File.
>discount
Nothing
这是我想看到的确切输出

$ less New.SubFile1.txt  
>owner
TimmyCoLtd
>shop1
grape
>price1
$5 

$ less New.SubFile2.txt 
>shop2
potato
>salesman
John
>price2 
$3

$ less New.SubFile3.txt  # duplicate a same file.
>discount
Nothing
如果我能在
子文件
源文件
之间找到相同的
存储
(所有
存储
价格
名称以
开头),然后从
源文件
移动
价格
美元
,并粘贴到
子文件

如果
源文件
子文件
之间没有相同的
存储
,只需为它们复制一个相同的文件,例如
New.SubFile3.txt


有什么好的python软件包吗?

一种有效的方法是从sourcefile创建字典。在dictionary
Id
中,列是键,其余列是值

from pathlib import Path

with open('source_file.txt') as fp:
    next(fp)
    res = dict(line.strip().split(' ', 1) for line in fp)

for file in Path('files').glob('*.txt'):
    with file.open() as fp, open(f'new_{file.stem}.txt', 'w') as fw:
        data = fp.readlines()
        for line in data:
            if line.startswith('>') and line.strip() in res:
                fw.write(''.join(data) + '\n' + '\n'.join(res[line.strip()].split()))
                break
        else:
            fw.writelines(data)

到目前为止,您尝试了什么不幸的是,我的编码能力只允许我使用相同的名称和行来完成工作,而不是我希望看到的如上所示的格式@你能帮忙吗?我相信这不会花费您太多的时间。输出必须在同一个文件或新文件中?不建议写入同一个文件创建一个新文件是绝对好的。谢谢,我知道这不会花费你太多时间。但是,如果我有大约1000个子文件,我可以简单地给出路径和文件夹名来替换这一行吗
files=['sub_file1.txt','sub_file2.txt']
id和数据之间是否有*正确?id,*data=fp.readlines()我的版本是2.7。这是python3中的一个功能。我在答案中添加了链接。为什么您仍在使用python2?backslah是转义字符使用双backslah或使用正斜杠
'F:\\'
'F://'
@Sakura而不是将结果存储在子文件中使用json文件(其中文件名为键,文件中的数据作为值列表)怎么样?