V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
coolair
V2EX  ›  Python

python 读取大文件输出错乱的问题

  •  
  •   coolair · 2014-04-20 10:12:30 +08:00 · 2959 次点击
    这是一个创建于 3659 天前的主题,其中的信息可能已经有所发展或是发生改变。


    文件内容是:


    为啥print输出乱了?怎么解决?
    12 条回复    1970-01-01 08:00:00 +08:00
    iptux
        1
    iptux  
       2014-04-20 10:32:38 +08:00
    cmd.exe?
    gkiwi
        2
    gkiwi  
       2014-04-20 10:38:53 +08:00
    你是指哪里乱了?文件里面内容很多吧,我刚刚测试个10000行的是ok的.
    coolair
        3
    coolair  
    OP
       2014-04-20 10:40:38 +08:00
    @gkiwi 本来应该输出“just a 00000000 word”,但是却输出了“worda 00000000”
    gkiwi
        4
    gkiwi  
       2014-04-20 10:46:44 +08:00
    @coolair 那小文件呢?你直接测试下`print 'just a %s word'%('xxx')`.这种问题不应该的发生的~环境呢?你写成py文件试下.
    coolair
        5
    coolair  
    OP
       2014-04-20 10:53:33 +08:00
    @gkiwi 小文件没问题,写成py文件一样出现错乱。
    silverfox
        6
    silverfox  
       2014-04-20 10:53:49 +08:00   ❤️ 3
    这里应该注意的是 Windows 系统中换行是 CRLF ('\r\n'),UNIX/OSX 是 LF ('\n')。
    上面的代码只是删除了 LF。因为 CR 仍然存在,所以在每行内容之后就折到下一行显示了。
    coolair
        7
    coolair  
    OP
       2014-04-20 11:00:46 +08:00
    @silverfox 呃,果然是这个问题,自己太不细心了,多谢!
    leyle
        8
    leyle  
       2014-04-20 11:05:06 +08:00
    直接用 line.rstrip() 是不是好用些?
    gkiwi
        9
    gkiwi  
       2014-04-20 11:06:18 +08:00
    @silverfox thanks;
    @coolair 酱紫:line.strip('\r').strip('\n')就能处理windows和unix了~
    9hills
        10
    9hills  
       2014-04-20 11:21:53 +08:00 via iPad   ❤️ 1
    @gkiwi line.strip()就行。。
    gkiwi
        11
    gkiwi  
       2014-04-20 11:26:13 +08:00
    @9hills 恩~
    Monad
        12
    Monad  
       2014-04-20 12:20:52 +08:00
    os.linesep
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3202 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:46 · PVG 18:46 · LAX 03:46 · JFK 06:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.