替换文件中的字典项

时间:2018-06-06 00:39:06

标签: python dictionary substitution

所以,我试图替换文件中的一些字符串,其中包含许多字符串。我试过了:

html_char = {
        '"' : '&quot',
        "'" : "'",
        '&' : '&',
...
}

def parser():
        f = open("file.txt", "w+")
        line = f.read()
        for key, val in html_char.items():
                line = line.replace(key,val)
        print("Writing succeded!")
        f.close()

parser()

但我没有成功。它打印"写成功!",尽管文件保持不变。

2 个答案:

答案 0 :(得分:0)

您有两种选择: 第一个(2个文件)

html_char = {
        '"' : '&quot',
        "'" : "'",
        '&' : '&',
}

def parser():
        f = open("file.txt", "r")
        f2 = open("file2.txt","w")
        line = f.read()
        for key, val in html_char.items():
            line = line.replace(key,val)
        f2.write(line)
        f.close()
        print("Writing succeded!")


parser()

第二:(1档)

html_char = {
        '"' : '&quot',
        "'" : "'",
        '&' : '&',
}

def parser():
        f = open("file.txt", "r")
        line = f.read()
        for key, val in html_char.items():
            line = line.replace(key,val)
        print("Writing succeded!")
        f.close()
        f = open("file.txt", "w")

        f.write(line)
        f.close()


parser()

答案 1 :(得分:0)

此代码将更改文件:

def parser(filename):
    with open(filename, "r+") as f:
        lines = []
        for line in f:
            lines.append(''.join([html_char.get(i, i) for i in line]))
        f.seek(0)
        f.writelines(lines)
        f.truncate()