我如何更改一个字符串中的字符串等于python中另一个文件中的字符串的所有代码。我会举例说明

我有文件 a.txt ,里面是: aaa = bbb,ccc = ddd,eee = fff,。而且我有多个文件( b.txt,c.txt ...),它们类似于: aaa = ggg,asd = fsd,eee = hhh,。我想创建一个新文件 combine.txt ,该文件将尝试在“ =” 签名之前找到相同的字符串,并用“ =”之后的另一个文件中的数据替换它们标志。因此,如果我们查找的是新文件,则新文件( combine.txt )如下所示: aaa = ddd,asd = fsd,eee = fff,使用split()方法(也许有更好的方法:D),但是我是编程新手,所以我需要帮助:)

file1 = open("/home/xxx/Desktop/Input1").read().split(" = ")

for line in a:

Type =  line.split(" = ")
a1 = Type[0]
c = Type[1]

file2 = [open("/home/xxx/Desktop/Input2").read()];

for line in file2:
Type =  line.split(" = ")
a2= Type[0]
d = Type[1]

output = open("/home/xxx/Desktop/Output1").write();

if(a1 == a2):
print(a1 + ' = ' + d)
ubiqual 回答:我如何更改一个字符串中的字符串等于python中另一个文件中的字符串的所有代码。我会举例说明

假设您的文本文件仅包含形式为aaa = bbb的作业行,例如,您可以将作业读入词典并将其合并,如下所示:

def dict_from_file(filename):   
    dict_file = {}
    with open(filename) as file1:
        for l in file1:
            arr=l.split("=")
            dict_file[arr[0].strip()] = arr[1].strip()
    return dict_file
file1_dict = dict_from_file("your_first_file.txt")
file2_dict = dict_from_file("your_second_file.txt")

print({**file1_dict,**file2_dict})

最后一行用第二个文件的值覆盖第一个文件的值。如果您需要更复杂的替换,则可以根据字典中的键在进一步的处理步骤中执行它们。您显然可以根据需要将其扩展到两个以上的文件。

,

如果我理解正确,您想用Input 2的值替换Input1的值吗?如果是这样,以下内容将为您服务:

def dict_from_file(filename):   
    dict_file = {}
    with open(filename) as file1:
        for l in file1:
            arr=l.split("=")
            dict_file[arr[0].strip()] = arr[1].strip()
    return dict_file

file1_dict = dict_from_file("Input1.txt")
file2_dict = dict_from_file("Input2.txt")

output_file = open("output.txt",'w')
output_file.write("\n".join([f'{k} = {v}' for k,v in {**file1_dict,**file2_dict}.items()]))
本文链接:https://www.f2er.com/3067116.html

大家都在问