一个python 读写文件时默认换行符设置的坑

本文详细解析了Python中文件操作时 newline 参数的作用。它控制读写模式下的换行处理,尤其在跨平台环境下可能导致问题。例如,Python在Windows上会将 转换为 ,这可能使Linux脚本无法正确识别。使用cat -A可以显示包含 的字符。理解这一行为对于确保文件在不同系统间兼容至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

            with open(target_file_name, "w", newline="\n") as f:
                f.write(content)
    newline controls how universal newlines works (it only applies to text
    mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
    follows:
        
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.

注意,如果没有设置newline,python在windows系统里面会将字符串里面的\n 写成文件里面 的\r\n,

而且,还会在读文件的时候把\r\n读成字符串里面的\n。

 

这种自作主张的默认操作会造成linux系统上的脚本文件无法被bash识别。

 

cat -A xx  可以在linux里面显示这个\r字符。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值