免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2041 | 回复: 4
打印 上一主题 下一主题

Python合并文本文件 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-04-11 13:38 |只看该作者 |倒序浏览
整理资料时,整出了高中时读过的一本书,还不错,不过当时是用电子辞典读的,没有书签功能,只能划成一个个的,现在读起来反倒麻烦。

于是就写个脚本把它们合并起来。
  1. # coding gbk
  2. #
  3. # author: GreatGhoul
  4. # email : greatghoul@gmail.com
  5. # blog  : http://greatghoul.javaeye.com

  6. import sys,os,msvcrt

  7. def join(in_filenames, out_filename):
  8.     out_file = open(out_filename, 'w+')
  9.    
  10.     err_files = []
  11.     for file in in_filenames:
  12.         try:
  13.             in_file = open(file, 'r')
  14.             out_file.write(in_file.read())
  15.             out_file.write('\n\n')
  16.             in_file.close()
  17.         except IOError:
  18.             print 'error joining', file
  19.             err_files.append(file)
  20.     out_file.close()
  21.     print 'joining completed. %d file(s) missed.' % len(err_files)
  22.     print 'output file:', out_filename
  23.     if len(err_files) > 0:
  24.         print 'missed files:'
  25.         print '--------------------------------'
  26.         for file in err_files:
  27.             print file
  28.         print '--------------------------------'

  29. if __name__ == '__main__':
  30.     print 'scanning...'
  31.     in_filenames = []
  32.     file_count = 0
  33.     for file in os.listdir(sys.path[0]):
  34.         if file.lower().endswith('[all].txt'):
  35.             os.remove(file)
  36.         elif file.lower().endswith('.txt'):
  37.             in_filenames.append(file)
  38.             file_count = file_count + 1
  39.     if len(in_filenames) > 0:
  40.         print '--------------------------------'
  41.         print '\n'.join(in_filenames)
  42.         print '--------------------------------'
  43.         print '%d part(s) in total.' % file_count
  44.         book_name = raw_input('enter the book name: ')
  45.         print 'joining...'
  46.         join(in_filenames, book_name + '[ALL].TXT')
  47.     else:
  48.         print 'nothing found.'
  49.     msvcrt.getch()
复制代码

论坛徽章:
0
2 [报告]
发表于 2012-07-16 15:56 |只看该作者
只是简单的把多个txt合并成一个文件,阅读起来还是很麻烦吧,不是有现成的把多个txt文件生成chm文件的工具。
只是为了用python练练手倒也说得过去。

论坛徽章:
0
3 [报告]
发表于 2012-07-16 22:39 |只看该作者
嗯,如果是do execise那就算了,否则就是舍近求远了,用cat一下子就全搞定了。

论坛徽章:
2
CU大牛徽章
日期:2013-04-17 11:46:28CU大牛徽章
日期:2013-04-17 11:46:39
4 [报告]
发表于 2012-07-16 23:44 |只看该作者
做成 html 吧

论坛徽章:
2
2015年迎新春徽章
日期:2015-03-04 09:55:28IT运维版块每日发帖之星
日期:2016-07-29 06:20:00
5 [报告]
发表于 2012-07-17 00:05 |只看该作者
从msvcrt模块判断,是windows上面的脚本
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP