免费注册 查看新帖 |

Chinaunix

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

如何能做到分割文件但不分割文件中的中文字符? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-07-26 01:44 |只看该作者 |倒序浏览
初学python,写一个小程序练手,要做的事情很简单,就是将一个文件,按照1M大小分割成多个小文件

#!/usr/bin/python

import sys;

if len(sys.argv) != 2:
    print("Usage: ", sys.argv[0], " FILENAME";
    exit()

in_file = sys.argv[1];
i = 0;
new_name = in_file;

# open the input file
f = open(in_file, "r";


while True:
    # create small files
    new_name = ''.join([new_name, str(i)]);
    i += 1;
    nf = open(new_name, 'w')
    # 1048576 = 1024 * 1024 = 1MB
    content = f.read(1048576)
    if not content:
        break
    nf.write(content);
    nf.close();
    print("create file: ", new_name);

f.close();
print("All done!";

本以为这样就ok了,结果使用一篇小说测试后,发现程序是有问题的,判断应该是程序把一个字符从中间截断,导致报错
请教下大家,如果能够实现“近似1M”的分割呢?

论坛徽章:
0
2 [报告]
发表于 2010-07-26 08:53 |只看该作者
我有时下载个小说之类的,如果小说太大,也用python分割成若干个较小的文件,但是分割的时候是按行分割,不是按字节分。因为如果按字节分,很有可能会将一行截断,看着挺不爽的。

但这种按字节分割,程序本身应该没有问题吧 。


我用你的代码试了一下,没发现问题。

python test.py test.txt
('create file: ', 'test.txt0')
('create file: ', 'test.txt01')
('create file: ', 'test.txt012')
('create file: ', 'test.txt0123')
('create file: ', 'test.txt01234')
('create file: ', 'test.txt012345')
('create file: ', 'test.txt0123456')
All done!

论坛徽章:
0
3 [报告]
发表于 2010-07-28 00:15 |只看该作者
使用 rb 读, 编码转换成 unicode, 分割,再转换成需要的编码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP