练习五十五:文件操作

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

一般方法(由于python是顺序,with 可以不缩进):

 1 with open(r'C:UsersPINPIN	estfile1.txt','r+') as f1:
 2     t1 = str(f1.readlines()[0])
 3     print(t1)
 4     with open(r'C:UsersPINPIN	estfile2.txt','r+') as f2:
 5         t2 = str(f2.readlines()[0])
 6         print(t2)
 7         with open(r'C:UsersPINPIN	estfile3.txt','w+') as f3:
 8             t3 = t1 + t2
 9             print(t3)
10             f3.write(t3)

执行结果:

12345
abcdefg
12345abcdefg

函数方法:

 1 def test(t1,t2):
 2     with open(t1,'r+') as f1:
 3         t1 = str(f1.readlines()[0])
 4     with open(t2,'r+') as f2:
 5         t2 = str(f2.readlines()[0])  
 6     with open(r'C:UsersPINPIN	estfile3.txt','w+') as f3:
 7         t3 = t1 + t2
 8         f3.write(t3)
 9         return(t3)
10 t1 = r'C:UsersPINPIN	estfile1.txt'
11 t2 = r'C:UsersPINPIN	estfile2.txt'
12 print(test(t1,t2))

执行结果:

12345abcdefg
原文地址:https://www.cnblogs.com/pinpin/p/10180216.html