python学习之写入文件及文件去重

需求大概就是将b文件写入a文件,然后再把a文件去重写入c文件
不需要导入任何库
想着放假无聊玩玩看吧~方法是Low了点,代码是烂了点,但是吧


我乐意
def write():
    a = open('a.txt', 'U').readlines()
    b = open('b.txt', 'U').readlines()
    # 要写入的文件
    ofile = open('a.txt', 'w')
    # 遍历读取所有文件,并写入到输出文件
    for txt in a:
        ofile.write(txt)
    ofile.write('\n')
    for txt in b:
        ofile.write(txt)
    ofile.write('\n')
    ofile.close()

def removal():
    # 将a去重后写入c
    i = 0
    read = "a.txt"  # old
    write = "c.txt"  # new
    lines_seen = set()
    outfile = open(write, "w")
    f = open(read, "r")
    for line in f:
        if line not in lines_seen:
            i += 1
            outfile.write(line)
            lines_seen.add(line)
    outfile.close()
    f.close()

if __name__ == '__main__':
    write()
    removal()


有点饿了。。先吃东西了,毕竟


人生苦短

你可能感兴趣的:(python学习之写入文件及文件去重)