菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 基础教程
(追記) (追記ここまで)

Python 练习实例99

Python 100例 Python 100例

题目:有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列), 输出到一个新文件C中。

程序分析:无。

程序源代码:

#!/usr/bin/python# -*- coding: UTF-8 -*-if__name__ == '__main__': importstringfp = open('test1.txt')a = fp.read()fp.close()fp = open('test2.txt')b = fp.read()fp.close()fp = open('test3.txt','w')l = list(a + b)l.sort()s = ''s = s.join(l)fp.write(s)fp.close()

运行以上程序前,你需要在脚本执行的目录下创建 test1.txt、test2.txt 文件。

以上程序执行成功后,打开 test3.txt 文件可以看到内容如下所示:

123456

Python 100例 Python 100例

AI 思考中...

2 篇笔记 写笔记

  1. #0

    Sue

    xxx***[email protected]

    30

    参考方法:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    def read(filename):
     f = open(filename,"r+")
     a = f.readlines()
     return a
    s = list("".join(read("test1.txt")+read("test2.txt")))
    s.sort()
    s1 = "".join(s)
    t = open("test.txt","w+")
    t.writelines(s1)
    t.close()
    

    Sue

    xxx***[email protected]

    9年前 (2017年08月17日)
  2. #0
    61

    python3的一个参考方法:

    # -*- coding: UTF-8 -*-
    with open('test1.txt') as f1, open('test2.txt') as f2, open('2.txt', 'w') as f3:
     for a in f1:
     b = f2.read()
     c = list(a + b)
     c.sort()
     d = ''
     d = d.join(c)
     f3.write(d)
    9年前 (2017年10月12日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /