简体   繁体   中英

Replace row data in file

I have two files: file1 , file2 .

In file1 I have lines with data that I'm parsing into list1 with skipping empty rows and making an elements lowercase:

file1:

dATa02
datA03

dAta04
with open('file1', 'r') as f:
    list1 = [l.lower() for l in (line.strip() for line in f) if l]

As a result, I get a data list list1 : [ 'data02', 'data03', 'data04' ]

In file2 I have a row: if [data] in [ "data01", "data02", "data03" ] { which constantly start with if [data] in

file2:

#somedata
if [data] in [ "data01", "data02", "data03" ] {
#somedate

I'm using regular expression for parsing data list:

import re
with open('/file2', 'r+') as f:
    for l in f:
        l_s = row.strip()
        if 'if [data] in ' in row_s:
            data1 = re.findall('"(.\w+)\"*', l_s)
            print(data1)

As a result I get another data list list2 : [ 'data01', 'data02', 'data03' ]

After getting two lists, I perform a comparison:

added = set(list1) - set(list2) #data04
deleted = set(list2) - set(list1) #data01

The question is: How to replace list2 from file2 to list1 from file1 ?

Maybe you can generate the list in file2 based on file1?

File 2 would look like this:

#somedata
with open('file1', 'r') as f:
    list1 = [l.lower() for l in (line.strip() for line in f) if l]

if [data] in list1 {
#somedate

Solved by code below:

if list1 == list2:
    print("Nothing changed...")
else:
    print("Found changes:")
    added_set = set(list1) - set(list2)
    deleted_set = set(list2) - set(list1)
    if added_set:
        print(f"New env: {added_set}")
    if deleted_set:
        print(f"Old env: {deleted_set}")

    env_new_str = (str(env_new).replace("'", '"'))
    env_prod_str = (str(env_prod).replace("'", '"'))

    try:
        s = open("file2").read()
        s = s.replace(env_prod_str, env_new_str)

        f = open("file2", 'w')
        f.write(s)
        print("Changed...")
    finally:
        f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM