python第四章课后习题(3)

有两个磁盘文件file_A和file_B,各存放一行字母,要求设计函数fun3,将这两个文件中的信息合并(按ASCII表顺序排列), 输出到一个新文件file_C中,要求使用pathlib库。

例如:A文件中内容:fca,B文件中内容:ebd,那么文件C中的结果应该为abcdef。

没啥难度

from pathlib import Path
def fun3(file_A='A.txt',file_B='B.txt',file_C='C.txt'):
    """
    Create the file "C.Txt", which contains the combined information of the two files(file_A and file_B).
    """
    path_A = Path(f'{path}/{file_A}')
    path_B = Path(f'{path}/{file_B}')
    with path_A.open('r',encoding='utf8') as fa:
        conA=fa.readline()
    with path_B.open('r',encoding='utf8') as fb:
        conB=fb.readline()
    newcon=''.join(sorted(conA+conB))
    with open(f'{path}/{file_C}','w',encoding='utf8') as fc:
        fc.write(newcon)

猜你喜欢

转载自blog.csdn.net/qq_53029299/article/details/114598078