首页 > 编程语言 >Python读写文件之换行符

Python读写文件之换行符

时间:2023-01-03 17:15:12浏览次数:60  
标签:换行符 Python nline2 读写 newline line1 test txt open

系统的换行符和路径分隔符

 

os模块可以获取当前系统的换行符和路径分隔符

 

windows操作系统

>>> os.linesep                        

'\r\n'

>>> os.sep                            

'\\'

 

linux操作系统

>>> import os

>>> os.linesep #换行符

'\n'

>>> os.sep #路径分隔符

'/'

 

 

open函数的newline参数

 

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

 

 

读取文件

 

  • newline = None(默认)

不指定newline,则默认开启Universal newline mode,所有\n, \r, or \r\n被默认转换为\n ;

  • newline = ''

不做任何转换操作,读取到什么就是什么

  • newline = 'the other legal values'

按照给定的换行符界定行

 

简单而言,读取文件时,newline参数默认,不管换行符是什么,都会被转换为\n

 

写入文件

 

  • newline = None(默认)

\n字符会被转换为各系统默认的换行符(os.linesep)

windows的换行符是\r\n,但是写入时,\r\n也会转换,转换为\r\r\n

  • newline = '' 或者newline = '\n'

不做任何操作

  • newline = 'the other legal values'

\n字符会被转换为给定的值

 

简单而言,使用字符串的rstrip()方法,去掉末尾的各种换行符

然后,加上\n,

写文件时,newline参数默认,\n字符会被转换为各系统默认的换行符(os.linesep)

 

 

示例1:编辑软件换行写,python原样读取和转换读取

 

向test.txt中写入如下内容:

 

with open('test.txt','r',newline='') as f:

																print(repr(f.read()))

with open('test.txt','r') as f:

																												print(repr(f.read()))

 

 

'line1\r\nline2'

'line1\nline2'

 

结果符合预期

写入时

向txt写入时,回车插入\r\n

读取时

newline='',不做转换,原样输出'line1\r\nline2'

newline = None,转换\r\n为\n

 

 

示例2:python转换写\n,python原样读取和转换读取

 

with open('test.txt','w'as f:
f.write('line1\nline2')

with open('test.txt','r',newline=''as f:
print(repr(f.read()))

 

 

with open('test.txt','r') as f:

												print(repr(f.read()))

 

 

'line1\r\nline2'

'line1\nline2'

 

这个结果符合预期

写入时

newline = None,\n字符会被转换为各系统默认的换行符,会将\n转换为\r\n

读取时

newline='',不会转换\r\n,原样输出

newline = None,会将\r\n转换为\n

 

 

示例3:python原样写\n,python原样读取和转换读取

 

 

with open('test.txt','w',newline='') as f:
    f.write('line1\nline2')

with open('test.txt','r',newline='') as f:

																														print(repr(f.read()))

with open('test.txt','r') as f:

																																										print(repr(f.read()))

 

 

'line1\nline2'

'line1\nline2'

 

结果符合预期

写入时

newline='',不会转换,原样写入'line1\nline2'

读取时

newline='',不会转换,原样输出'line1\nline2'

newline = None,会转换\r\n为\n,但是没有\r\n,所以显示的\n,也没问题

 

 

 

去掉字符串首尾的空白字符

 

\n,\r,\t,空格等

字符串的strip(),lstrip(),rstrip()

 

str.strip去掉字符串头和尾的空白字符

 

>>> help(str.strip)

                            

Help on method_descriptor:

strip(...)

S.strip([chars]) -> str

Return a copy of the string S with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

 

str.lstrip 去掉字符串头的空白字符

 

>>> help(str.lstrip)

                            

Help on method_descriptor:

lstrip(...)

S.lstrip([chars]) -> str

Return a copy of the string S with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

 

str.rstrip去掉字符串尾的空白字符

 

>>> help(str.rstrip)

                            

Help on method_descriptor:

 

rstrip(...)

S.rstrip([chars]) -> str

Return a copy of the string S with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

 

拓展:linux和windows文件之间的拷贝

 

假设有一个linux下的unix.txt文件, 那么, 它在文件中的换行标志是:\n, 现在把unix.txt拷贝到Windows上, Windows找不到unix.txt中的\r\n, 所以,对于Windows而言, 压根就没有发现unix.txt有任何换行, 所以, 我们从Windows上看到的unix.txt文件显示在一行里面。win10的txt文件中\n也能识别为换行符了

 

同理, 假设Windows上有一个dos.txt文件, 那么, 它在文件中的换行标志是\r\n, 现在拷贝到linux下, linux遇到文件中的\n, 认为是换行, 至于其他的, 认为是正常的字符。 如此一来, \r就被当成了文件的正常部分,当这个文件是可执行脚本时,就会报错。

 

win7中只有\r\n被识别为换行符

 

>>> with open('test.txt','w',newline='') as f:

    f.write('line1\rline2\nline3\r\nline4')

24

>>> with open('test.txt','r',newline='') as f:

    f.read()

'line1\rline2\nline3\r\nline4'

 

 

win10中,\r,\n,\r\n都可以识别为换行

 

>>> b'\r'.hex()                            

'0d'

>>> b'\n'.hex()                        

'0a'

 

以上\r十六进制是0d,\n十六进制是0a

 

 

示例1:\r

 

with open('test.txt','w',newline=''as f:
f.write('line1\rline2')
with open('test.txt','r',newline=''as f:
print(repr(f.read()))
with open('test.txt','r'as f:
print(repr(f.read()))

 

'line1\rline2'

'line1\nline2'

 

\r能换行

 

 

示例2:\n

 

with open('test.txt','w',newline=''as f:
f.write('line1\nline2')
with open('test.txt','r',newline=''as f:
print(repr(f.read()))
with open('test.txt','r'as f:
print(repr(f.read()))

 

'line1\nline2'

'line1\nline2'

 

\n能换行

 

示例3:\r\n

 

with open('test.txt','w',newline=''as f:
f.write('line1\r\nline2')
with open('test.txt','r',newline=''as f:
print(repr(f.read()))
with open('test.txt','r'as f:
print(repr(f.read()))

 

'line1\r\nline2'

'line1\nline2'

 

 

 

示例4:\r\r\n

 

with open('test.txt','w',newline=''as f:
f.write('line1\r\r\nline2')
with open('test.txt','r',newline=''as f:
print(repr(f.read()))
with open('test.txt','r'as f:
print(repr(f.read()))

 

'line1\r\r\nline2'

'line1\n\nline2'

 

\r和\r\n都被识别为换行符

 

示例5:\r,newline=None

 

\n字符会被转换为各系统默认的换行符(os.linesep)

这里没有\n

 

with open('test.txt','w'as f:
f.write('line1\rline2')
with open('test.txt','r',newline=''as f:
print(repr(f.read()))
with open('test.txt','r'as f:
print(repr(f.read()))

 

'line1\rline2' #不做转换,原样读取

'line1\nline2' #\r转换为\n

 

 

示例6:\n,newline=None

 

\n字符会被转换为各系统默认的换行符(os.linesep)

 

with open('test.txt','w'as f:
f.write('line1\nline2')
with open('test.txt','r',newline=''as f:
print(repr(f.read()))
with open('test.txt','r'as f:
print(repr(f.read()))

'line1\r\nline2' #原样读取,不做转换,可以看到\n在写入时转换为\r\n

'line1\nline2' #转换读取,\r\n转换为\n

 

示例7:\r\n,newline=None

 

\n字符会被转换为各系统默认的换行符(os.linesep)

 

with open('test.txt','w'as f:
f.write('line1\r\nline2')
with open('test.txt','r',newline=''as f:
print(repr(f.read()))
with open('test.txt','r'as f:
print(repr(f.read()))

 

'line1\r\r\nline2' #原样读取,不做转换,\r\r\n并没有转换为\r\r\r\n,检测到了\r\n

'line1\n\nline2' #转换读取,\r\n转换为\n

 

 

python中,只有\n被识别为换行符

 

 

 

word中,\r,\n,\r\n都可以识别为换行

 

>>> print('line1\rline2')                            

line1 line2

 

>>> print('line1\nline2')                            

line1

line2

 

>>> print('line1\r\nline2')                            

line1

line2

 

>>> print('line1\r\r\nline2')

line1

line2

  分类: python

标签:换行符,Python,nline2,读写,newline,line1,test,txt,open
From: https://www.cnblogs.com/qiumingcheng/p/17022797.html

相关文章

  • Python Tkinter教程
    1控件Tkinter模块提供了2种Toplevel控件和许多基本控件,目前已包括15种,每种控件都有很多属性  简单示例:1fromtkinterimport*#导入tkinter模块【必要步骤】2......
  • python 中os和sys模块常用方法
    OS常用方法os.remove()删除文件os.rename()重命名文件os.walk()生成目录树下的所以文件名os.chdir()改变目录os.mkdir/makedirs创建目录/多层目录os.rmdir/removed......
  • python脚本性能分析
    1.python脚本性能分析cProfile思路使用cProfile模块生成脚本执行的统计信息文件使用pstats格式化统计信息,并根据需要做排序分析处理使用snakeviz图形化页面显示2.cP......
  • opencv-python同时调用两个摄像头
    importcv2importnumpyasnpcapture=cv2.VideoCapture(0)capture_usb=cv2.VideoCapture(2)#打开自带的摄像头ifcapture.isOpened()andcapture_usb.isOpene......
  • python + appium 常用公共方法封装
    appium程序下载安装见之前的帖子:https://www.cnblogs.com/gancuimian/p/16536322.htmlappium环境搭建见之前的帖子:https://www.cnblogs.com/gancuimian/p/16557576.html......
  • Python 每天一个知识点(预计为期100天)第一天
    列表的基本操作:一,列表的定义:1.列表之内的元素不要求同一类型,所以极为方便2.列表的本质上是容器,最常见的是包含字符串,数字,自定义的对象3.根据不同编译器,lis......
  • 【Ubuntu】Ubuntu安装python虚拟环境
    1.准备环境Ubuntu20.04LTS1.1安装virtulenv和virtulenvwrappersudopip3installvirtulenvsudopip3installvirtulenvwrapper1.2配置虚拟环境存放目录先在$HOM......
  • python技能树——删除字符串的空格
    python技能树——删除字符串的空格来看一道题:描述牛牛、牛妹和牛可乐都是Nowcoder的用户,某天Nowcoder的管理员由于某种错误的操作导致他们的用户名的左右两边增加了一......
  • python技能树——字符串大小写运用
    python技能树——字符串大小及运用来看一道题:描述牛牛、牛妹和牛可乐都是Nowcoder的用户,某天Nowcoder的管理员希望将他们的用户名以某种格式进行显示,现在给定他们三......
  • python——时间格式转换,time.strftime()与time.strptime()
    strftime: 将给定格式的日期时间对象转换为字符串。日期时间对象=>字符串,控制输出格式strptime:将字符串解析为给定格式的日期时间对象。字符串=>日期时间对象,解析字符串......