zoukankan      html  css  js  c++  java
  • python 换行符的识别问题,Unix 和Windows 中是不一样的

    关于换行符的识别问题,在Unix 和Windows 中是不一样的(分别是n 和rn)。默认情况下,Python 会以统一模式处理换行符。这种模式下,在读取文本的时候,Python 可以识别所有的普通换行符并将其转换为单个nn 字符。类似的,在输出时会将换行符nn 转换为系统默认的换行符。如果你不希望这种默认的处理方式,可以给open() 函数传入参数newline='' ,就像下面这样:
    # Read with disabled newline translation
    with open('somefile.txt', 'rt', newline='') as f:
    ...
    为了说明两者之间的差异,下面我在Unix 机器上面读取一个Windows 上面的文本文件,里面的内容是hello world! :

    >>> # Newline translation enabled (the default)
    >>> f = open('hello.txt', 'rt')
    >>> f.read()
    'hello world!
    
    
    
    >>> # Newline translation disabled
    >>> g = open('hello.txt', 'rt', newline='')
    >>> g.read()
    'hello world!
    ''
    

    转载于:https://www.cnblogs.com/baxianhua/p/10190486.html

  • 相关阅读:
    linux初始化宏__init, __exit
    linux内核initcall
    常用命令合集
    df
    ln
    cat
    grep
    find
    IE11浏览器传时间格式不兼容,c.a.d.c.advice.AdcDaBaseExceptionAdvice : JSON parse error
    js 图片不保存的回显功能/图片尺寸验证/图片大小验证 /图片类型验证
  • 原文地址:https://www.cnblogs.com/twodog/p/12135391.html
Copyright © 2011-2022 走看看