文件读写和字符串、列表的排序

文件操作部分:

使用 with open as:语法的好处是不用手动关闭文件

排序部分:

1、python中的字符串类型是不允许直接修改元素的。必须先把要排序的字符串放在容器里,如list。
2、python中list容器的sort()函数没有返回值。所以在python中对字符串排序需要好几行代码:
s="string"
l=list(s)
l.sort()
s="".join(l)
print s 'ginrst'

少BB上代码:

问题:有两个磁盘文件file.txt和file2.txt,各存放一行字母数字等,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件file3.txt中?

with open('file.txt', encoding='utf-8') as fd1, open('file2.txt', encoding='utf-8') as fd2, 
        open('file3.txt', 'w', encoding='utf-8') as fd3:
    str1 = str2 = str3 = ''
    for i in fd1.read():
        str1 += i
    for j in fd2.read():
        str2 += j
    str3 = str1 + str2             #str3排序此时他是一个字符串,字符串不能改变,所以要转换为列表使用sort()
    str3 = list(str3)
    str3.sort()
    s = ''.join(str3)              #将排好的列表转换为字符串 后写入文件
    fd3.write(s)
原文地址:https://www.cnblogs.com/Mr-wangxd/p/9385102.html