python_open函数中newline参数详解

问题的由来

我在读pythoncsv模块文档 看到了这样一句话

如果 csvfile 是文件对象,则打开它时应使用 newline=”。
其备注:如果没有指定 newline=”,则嵌入引号中的换行符将无法正确解析,并且在写入时,使用 \r\n 换行的平台会有多余的 \r 写入。由于 csv 模块会执行自己的(通用)换行符处理,因此指定 newline=” 应该总是安全的。

我就在思考open函数中的newline参数的作用,因为自己之前在使用open函数时从来没有设置过newline参数,仅从上面官方给的备注理解newline参数可以帮助处理换行符解析的问题

并且查阅得知不同操作系统换行符并不一致:

Unix 的行结束约定 ‘\n’、Windows 的约定 ‘\r\n’ 以及旧版 Macintosh 的约定 ‘\r’

打破了我原本观念以为的换行符就是\n

python官方文档对newline参数解释:

newline 控制 universal newlines 模式如何生效(它仅适用于文本模式)。它可以是 None,”,’\n’,’\r’ 和 ‘\r\n’。它的工作原理:
从流中读取输入时,如果 newline 为 None,则启用通用换行模式。输入中的行可以以 ‘\n’,’\r’ 或 ‘\r\n’ 结尾,这些行被翻译成 ‘\n’ 在返回呼叫者之前。如果它是 ”,则启用通用换行模式,但行结尾将返回给调用者未翻译。如果它具有任何其他合法值,则输入行仅由给定字符串终止,并且行结尾将返回给未调用的调用者。
将输出写入流时,如果 newline 为 None,则写入的任何 ‘\n’ 字符都将转换为系统默认行分隔符 os.linesep。如果 newline 是 ” 或 ‘\n’,则不进行翻译。如果 newline 是任何其他合法值,则写入的任何 ‘\n’ 字符将被转换为给定的字符串。

从这也就理解了为什么原本使用open()写的时候用\n就可以表示换行以及读文本文件时行尾会返回\n

  • 写入的时候没有指定newline参数会将\n翻译成系统默认的行分割符(\r\n)
  • 读的时候没有指定newline参数会将行分割符(\r\n)翻译为\n
回到上文,那为什么在读写csv文件时就要设置newline=”呢?

pythoncsv官方文档解释了这一问题(这也就引入了第二种方法解决换行的问题,我在后面会介绍到)

Dialect.lineterminator
放在 writer 产生的行的结尾,默认为 ‘\r\n’。
注解 reader 经过硬编码,会识别 ‘\r’ 或 ‘\n’ 作为行尾,并忽略 lineterminator。未来可能会更改这一行为。

用白话说就是 writerow()方法在写入一行数据时在行尾都 会跟一个默认换行符(\r\n)(即csv是将’一行数据\r\n’写入内存,此时这一行数据还在内存中,还没有写入文件)之后执行代码真正在向文件写入时根据不同newline参数进行翻译
而在向txt文件 使用write()方法写入内容时是我们手动添加换行符\n(内存中的数据就是我们写入的内容,并 不会隐式添加其他内容)之后执行代码真正在向文件写入时根据newline参数进行翻译,这就是二者的区别
具体流程:
newline=”
writer.writerow(‘line’) 实际是向内存中写入’line\r\n’ –》 执行代码,写入文件,根据newline=”,将不进行翻译 –》文件最终写入’line\r\n’
newline=None(默认)
f.write(‘line\n’) 直接将’line\n’写入内存 –》 执行代码,写入文件,根据newline=None,将\n翻译为\r\n –》文件最终写入’line\r\n’

python_open函数中newline参数详解

; 具体实例

case1: w newline=” r newline=”
import csv
with open("test.csv","w",encoding='utf-8',newline='') as csvfile:
        writer=csv.writer(csvfile)
        writer.writerow(["num","name","grade"])
        writer.writerows([[1,'luke','96'],[2,'jack','85'],[3,'nick','84']])
with open("test.csv","r",encoding='utf-8',newline='') as csvfile:
        txtdata=csvfile.read()
txtdata

python_open函数中newline参数详解
case2: w newline=’\r’ r newline=”
import csv
with open("test.csv","w",encoding='utf-8',newline='\r') as csvfile:
        writer=csv.writer(csvfile)
        writer.writerow(["num","name","grade"])
        writer.writerows([[1,'luke','96'],[2,'jack','85'],[3,'nick','84']])
with open("test.csv","r",encoding='utf-8',newline='') as csvfile:
        txtdata=csvfile.read()
txtdata

python_open函数中newline参数详解
case3: w newline=’\r\n’ r newline=”
import csv
with open("test.csv","w",encoding='utf-8',newline='\r\n') as csvfile:
        writer=csv.writer(csvfile)
        writer.writerow(["num","name","grade"])
        writer.writerows([[1,'luke','96'],[2,'jack','85'],[3,'nick','84']])
with open("test.csv","r",encoding='utf-8',newline='') as csvfile:
        txtdata=csvfile.read()
txtdata

python_open函数中newline参数详解
case4: w newline=None r newline=None
import csv
with open("test.csv","w",encoding='utf-8',newline=None) as csvfile:
        writer=csv.writer(csvfile)
        writer.writerow(["num","name","grade"])
        writer.writerows([[1,'luke','96'],[2,'jack','85'],[3,'nick','84']])
with open("test.csv","r",encoding='utf-8',newline=None) as csvfile:
        txtdata=csvfile.read()
txtdata

python_open函数中newline参数详解
case5: 文件写入为\r\r\n 文件读取 newline=’\r’
with open("test.csv","r",encoding='utf-8',newline='') as csvfile:
    txtdata=csvfile.read()
txtdata
import csv
with open("test.csv","r",encoding='utf-8',newline='\r') as csvfile:
    content = csv.reader(csvfile)
    for i in content:
        print(i)

python_open函数中newline参数详解
csv.reader是如何读取\r\r\n的:读取时遇到\r认为一行结束了,再一次遇到\r同样认为一行结束(因而返回了空串列表),遇到\n无法解释–》报错
case6:文件写入为\r\r\n 文件读取 newline=’\n’
with open("test.csv","r",encoding='utf-8',newline='') as csvfile:
    txtdata=csvfile.read()
txtdata
import csv
with open("test.csv","r",encoding='utf-8',newline='\n') as csvfile:
    content = csv.reader(csvfile)
    for i in content:
        print(i)

python_open函数中newline参数详解
case7:文件写入为\r\r\n 文件读取newline=’\r\n’
with open("test.csv","r",encoding='utf-8',newline='') as csvfile:
    txtdata=csvfile.read()
txtdata
import csv
with open("test.csv","r",encoding='utf-8',newline='\r\n') as csvfile:
    content = csv.reader(csvfile)
    for i in content:
        print(i)

python_open函数中newline参数详解
case8:文件写入为\r\r 文件读取 newline=’\r’
with open("test.csv","r",encoding='utf-8',newline='') as csvfile:
    txtdata=csvfile.read()
txtdata
import csv
with open("test.csv","r",encoding='utf-8',newline='\r') as csvfile:
    content = csv.reader(csvfile)
    for i in content:
        print(i)

python_open函数中newline参数详解

第二种方法:通过设置csv.writer方法中的lineterminator参数

上面提到lineterminator参数控制writer写入每一行后跟的隐式结束符,默认为’\r\n’,因此我们需要要设置lineterminator=’\n’,读取时也不需要设置newline参数即可获得想要的效果

import csv
with open("test.csv","w",encoding='utf-8') as csvfile:
    writer=csv.writer(csvfile,lineterminator='\n')
    writer.writerow(["num","name","grade"])
    writer.writerows([[1,'luke','96'],[2,'jack','85'],[3,'nick','84']])
with open("test.csv","r",encoding='utf-8') as csvfile:
    lst=csv.reader(csvfile)
    csvfile.seek(0)
    txtdata = csvfile.read()
    csvfile.seek(0)
    for i in lst:
        print(i)
txtdata

python_open函数中newline参数详解python_open函数中newline参数详解

Original: https://blog.csdn.net/Reborn214/article/details/123974467
Author: 我是个烧饼啊
Title: python_open函数中newline参数详解

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/730524/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球