python 批量将文件B对应内容插入文件A对应位置

文件A内含有地名,文件B是地名对应的坐标。

先从文件A找到地名,然后去B查到地名,提取地名之后特定格式的坐标,写入文件A。

有参考各种,侵权请联系我删除。

是小白,所以只做到了能用而已。

#!/usr/bin/python
# -*- coding: utf-8 –*-
import re

f1 = open("file1.txt", "r+", encoding='utf-8')  # read and write
print("done open f1")
line1 = f1.readlines()
f1.seek(0, )

f2 = open("file2.txt", "r+", encoding='utf-8')  # read only
print("done open f2\n")
line2 = f2.readlines()

# read file1 from beginning to end
for line0 in line1:
    # if "name" is in this line
    flag1 = re.search("name", line0)
    if flag1:
        # find place between " "
        place = line0.split("\"")[3]
        print("find place:", place)
        # this is the line where place is, tab = 0,1,2,3,...
        line1_copy = line1[:]
        tab = line1_copy.index(line0)

        # # add a comma in: line1_copy[tab+1]
        # line1_copy[tab + 1] = (str(line1_copy[tab + 1]) + ',')
        # print("added comma")

        # find place in file2
        for line in line2:
            flag2 = re.search(place, line)
            if flag2:
                # find words between []
                try:
                    location = re.findall(re.compile(r'[\[](.*?)[\]]', re.S), line)[0]
                    print("find location:", location)
                except:
                    print("Error")

                # put location in file1
                if location:
                    # find correct line and write
                    new_line = ("    \"coordinate\": \"[" + location + "]\"\n")
                    line1.insert(tab + 2, new_line)
                    # print(line1)
                    break

# write
print("start writing location")
f1.writelines(line1_copy)
print("done writing location in f1\n")

f1.close()
f2.close()
print("files closed")

写入前的文件A和B:

写入之后的效果:

后来给每行value末尾插入了逗号。

# add comma
for line0 in line1:
    # if "value" is in this line
    flag1 = re.search("value", line0)
    if flag1:
        # find value between " "
        value = line0.split("\"")[3]
        print("find value:", value)
        # this is the line where value is(tab = 0,1,2,3,...), add a comma
        line1_copy2 = line1[:]
        tab = line1_copy2.index(line0)
        adapt_line = ("    \"value\": \"" + value + "\",\n")
        line1[tab] = adapt_line
        print("added comma")

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值