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

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

 1 with open(r'C:\Users\PINPIN\test\file1.txt','r+') as f1:
 2     t1 = str(f1.readlines()[0])
 3     print(t1)
 4     with open(r'C:\Users\PINPIN\test\file2.txt','r+') as f2:
 5         t2 = str(f2.readlines()[0])
 6         print(t2)
 7         with open(r'C:\Users\PINPIN\test\file3.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:\Users\PINPIN\test\file3.txt','w+') as f3:
 7         t3 = t1 + t2
 8         f3.write(t3)
 9         return(t3)
10 t1 = r'C:\Users\PINPIN\test\file1.txt'
11 t2 = r'C:\Users\PINPIN\test\file2.txt'
12 print(test(t1,t2))

执行结果:

12345abcdefg

相关文章:

  • 2021-11-15
  • 2021-05-26
  • 2021-11-25
  • 2021-07-02
  • 2022-01-13
  • 2021-09-27
  • 2021-09-28
  • 2021-06-14
猜你喜欢
  • 2021-06-21
  • 2021-10-20
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
  • 2021-12-23
  • 2021-06-26
相关资源
相似解决方案