第3章 习题3.12 合并文件
来源:互联网 发布:呢大衣起球 知乎 编辑:程序博客网 时间:2024/05/17 02:47
#!/usr/bin/env python3#合并两个文件, 提示是用户自己创建还是查找import osdef showmenu(): print('--------------------------------') print('| |') print('| 1. 合并两个已存在的文件 |') print('| 2. 合并两个不存在的文件 |') print('| 3. 退出 |') print('| |') print('---------------------------------') userchoose = input(':') return userchoosedef find_file1_file2(): file1 = input('文件1:') file2 = input('文件2:') file3 = input('请输入合并后的文件:') if (not os.path.exists(file1)): print('没有 %s 文件!' % file1) if (not os.path.exists(file2)): print('没有 %s 文件!' % file2) if os.path.exists(file3): print('文件 %s 已存在!' % file3) return 0 try: file1_fp = open(file1, 'r') file2_fp = open(file2, 'r') file3_fp = open(file3, 'w') except: print('打开文件出错!') return 0 file3_fp.writelines(['%s' % eachline for eachling in file1_fp]) file3_fp.writelines(['%s' % eachline for eachling in file2_fp]) file1_fp.close() file2_fp.close() file3_fp.close() input() return 0def create_file1_file2(): file1_data = [] file2_data = [] while True: file1 = input('创建文件1:') if os.path.exists(file1): print('文件 %s 已存在!' % file1) else: break file1_fp = open(file1, 'w') while True: file1_read = input('(输入#号退出编辑)>') if file1_read == '#': break else: file1_data.append(file1_read) #写入文件 file1_fp.writelines([('%s%s') % (eachline, os.linesep) for eachline in file1_data]) file1_fp.close() file1_fp = open(file1, 'r') while True: file2 = input('创建文件2:') if os.path.exists(file2): print('文件 %s 已存在!' % file2) else: break file2_fp = open(file2, 'w') while True: file2_read = input('(输入#号退出编辑)>') if file2_read == '#': break else: file2_data.append(file2_read) file2_fp.writelines(['%s%s' % (eachline, os.linesep) for eachline in file2_data]) file2_fp.close() file2_fp = open(file2, 'r') #合并后的文件 while True: sumfile = input('请输入合并后的文件名:') if os.path.exists(sumfile): print('%s 已存在!') else: break sumfile_fp = open(sumfile, 'w') sumfile_fp.writelines(['%s' % earchline for earchline in file1_fp]) sumfile_fp.writelines(['%s' % earchline for earchline in file2_fp]) sumfile_fp.close() file1_fp.close() file2_fp.close() return 0while True: userchoose = showmenu() if userchoose == '1': find_file1_file2() elif userchoose == '2': create_file1_file2() elif userchoose == '3': break else: print('你选择错误,请重新选择!')
0 0
- 第3章 习题3.12 合并文件
- 第3章习题3
- c++第3章习题
- 【第2章 习题3】
- 学习Opencv第3章课后习题
- Accelerated C++ 习题解答 第3章
- 《Python核心编程》第3章 习题
- 第3章 认识HDFS习题
- 算法导论第3章习题解析
- 第7章 习题
- 第8章习题
- 第9章合并
- 第16章习题2
- 【第2章 习题4】
- 【第2章 习题5】
- 【第2章 习题6】
- 第4章 子程序习题
- 《python第8章习题》
- android4.0以上网络访问为什么要开线程,已经Handler的使用
- Android studio at ubuntu 14.04, run ADB error:没有那个文件或目录
- start
- sql where 1=1和 0=1 的作用
- LeetCode(115) Distinct Subsequences
- 第3章 习题3.12 合并文件
- Get the page name in asp.net web page
- 解析国足末战:上下半场如两队 国足锁定世预赛种子队
- 您好,欢迎分享关于携程网站的使用感受和功能建议!
- HDU 4405 Aeroplane chess(期望DP)
- Guava学习笔记-Function,Predicate
- 能够使自己的优化水平,有一定性晋升。
- Windows下利用Cygwin登录远程Linux
- Python 对字典元素的赋值 (字典key和value均为组合类型)