![](/img/trans.png)
[英]copy one dictionary from a python file and paste it to corresponding json file
[英]Search, and copy paste a text to corresponding file using pandas python
假设我有一个包含本地商店产品价格的源文件。
$ less SourceFile.txt # see this file using less function in terminal.
Store Price Dollars
>shop1 >price1 $5
>shop2 >price2 $3
而且,每个Store
都有一些称为sub files
营销数据,不幸的是不完整。
$ 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
如果我可以在Sub File
和Source File
之间找到相同的Store
(所有Store
和Price
名称以>
开头),然后将Price
和Dollars
从Source File
移动并粘贴到Sub File
。
如果Source File
和Sub File
之间没有相同的Store
,那么只需为它们复制一个相同的文件,例如New.SubFile3.txt
。
有什么好的python包来制作它吗?
一种有效的方法是从源文件创建字典。 在字典中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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.