推荐学习书目
› 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 · Apr 20, 2014 · 3945 views
    This topic created in 4605 days ago, the information mentioned may be changed or developed.


    文件内容是:


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