惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
O
OpenAI News
V
V2EX
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
S
Schneier on Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
小众软件
小众软件
L
LINUX DO - 热门话题
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - Franky
Security Latest
Security Latest
S
SegmentFault 最新的问题
Project Zero
Project Zero
Spread Privacy
Spread Privacy
K
Kaspersky official blog
J
Java Code Geeks
V
Vulnerabilities – Threatpost
C
Cisco Blogs
C
CERT Recently Published Vulnerability Notes
月光博客
月光博客
T
The Exploit Database - CXSecurity.com
L
Lohrmann on Cybersecurity
人人都是产品经理
人人都是产品经理
博客园 - 三生石上(FineUI控件)
Scott Helme
Scott Helme
WordPress大学
WordPress大学
量子位
T
Threat Research - Cisco Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
AWS News Blog
AWS News Blog
Help Net Security
Help Net Security
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Simon Willison's Weblog
Simon Willison's Weblog
S
Secure Thoughts
博客园 - 【当耐特】
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
V
Visual Studio Blog
Last Week in AI
Last Week in AI
T
Tailwind CSS Blog
腾讯CDC
Cyberwarzone
Cyberwarzone
IT之家
IT之家
GbyAI
GbyAI
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
云风的 BLOG
云风的 BLOG
T
Troy Hunt's Blog
D
Docker

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN Mintty Tips and Configurations Generating Table of Contents for Markdown with Tagbar Convert Python Script to Exe on Windows with Pyinstaller Ubuntu on Windows Missing after Windows Update 使用代理加速 Mac 终端下载速度 My Experience with Several Zsh Plugin Managers 深圳租房小记 How to Install zplug inside Docker Container Why don't settings inside bashrc or bash_profile take effect? Setting Up Locale in Linux 谷歌 Adsense 申请及在 Hugo 中的配置 How to Write Algorithm Pseudo Code in LaTeX Nifty Nvim Techniques That Make My Life Easier -- Series 4 A Few Grammar Questions in Writing How to Read and Write Images with Unicode Paths in OpenCV Creating A Professional Table in LaTeX with booktabs How to Create Proper Folding for Vim/Nvim Configuration Linux Tips and Tricks -- s1 JPEG Image Orientation and Exif How Do I Show the Current File Path In Neovim? JPEG Image Quality in PIL Difference between view, reshape, transpose and permute in PyTorch Convert PIL or OpenCV Image to Bytes without Saving to Disk Fast Movement and Navigation Inside Vim or Neovim Unintuitive Behaviour of Case Sensitivity in Python glob Binding Keys in Zsh 几把机械键盘试用体验 Nvim Autocompletion with Deoplete Converting Markdown to Beautiful PDF with Pandoc Exclusive and Inclusive Motion in Neovim/Vim Nifty Nvim Techniques Which Make My Life Easier -- Series 3 Why Doesn't Jedi Autocompletion Work for Some Methods Vim-like Editing inside Browser Markdown 生成 HTML 时汉字之间出现多余空格问题 小米 9 安装谷歌商店(Google Play Store)与相关配置 Create Mappings That Take A Count in Neovim Spell Checking in Nvim English Words Completion inside Neovim/Vim How to Use Python Inside Vim Script with Neovim Nifty Little Nvim Techniques to Make My Life Easier -- Series 2 Setting up Ultisnips for Neovim Mac 上罗技 M590 鼠标设置 Nifty Little Nvim Techniques to Make My Life Easier -- Series 1 A Complete Guide on Writing LaTeX with Vimtex in Neovim Manipulating Images with Alpha Channels in Pillow Sublime Text Regular Expression Cheat Sheet Cropping Rotated Rectangles from Image with OpenCV Boosting Your Productivity on Terminal with Zsh and Plugins 最新版 Rime 输入法使用 (2022 更新) Display Image with Pillow inside Ubuntu on Windows Faster Directory Navigation with z.lua Cmder Advanced Configurations Nvim-qt Settings on Windows 10 Tmux Plugin Install and Management How to Debug Python Code in Terminal Markdown Writing and Previewing in Neovim -- A Complete Guide Line Number Settings for More Efficient Movement in Neovim 两个大规模中文语料库介绍以及处理 Windows 系统下几款程序员不可不用的神器 我的 2018 阅读清单 A Complete Guide to Neovim Configuration for Python Development Two Issues Related to ImageFont Module in PIL 在 Listary 中调用 GoldenDict 或欧路词典查单词 Reading and Writing Text Files on Windows The Mathematics behind Font Shapes --- Bézier Curves and More 快速识别图片字体:字体识别工具介绍 Deoplete Failed to Load at Startup after Updating Python neovim Package What Is The Difference between pip, pip3 and pip3.6 Shipped with Anaconda3? Windows 10 系统下 Neovim 安装与配置 How to Use shutil.move() on Windows and Linux
How Is Newline Handled in Python and Various Editors?
2018-12-08 · via jdhao's digital space

Every programmer knows newline character, but may be not so familiar. In this post, I want to share what I have learned about newline handling in various cases.

Newline characters on different platforms#

Due to historical reasons, different platforms use different characters to signify a new line. On Windows, <CR><LF> (byte code 0x0D0x0A) is used to represent newline. On Linux, <LF>(byte code 0x0A) is used to represent newline. On older Mac1, <CR>(byte code 0x0D) is used.

<CR> and <LF> date back to the old time when typewriters is used for printing texts on paper. <CR> represents carriage return, which means to put the carriage to its left-most position. <LF> represents line feed, which means to move the paper a little higher so that you can type on a new line. You can see that these two actions combined will start a new line ready for typing.

Newline handling in Python#

Python 2 and Python 3 have different way of handling newlines. In Python 2, there is a universal newline mode, which means that no matter what the file line ending is, it will all be translated to \n when reading files with mode specifier rU.

In Python 3, things have changed. The old U mode specifier has been deprecated in favor of a newline parameter in the open() method. According to the documentation:

newline controls how universal newlines mode works (it only applies to text mode). It can be None, ‘’, ‘\n’, ‘\r’, and ‘\r\n’. It works as follows:

  • When reading input from the stream, 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 newlines mode is enabled, but line endings are returned to the caller untranslated.
  • When writing output to the stream, 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.

when reading text files, newline is None by default, which means that system-dependent newline will be quietly replaced by \n. If you are not aware of this behavior, you may get into trouble. For example, when you read a file with \r\n line ending and want to split the text into lines on Windows platform, if you use the following snippet:

with open("some_file.txt", "r") as f:
    text = f.read()
lines = text.split(os.linesep)

you will not be able to split the text into lines. That is because on Windows platform, os.linesep is \r\n. But Python has secretly translated the \r\n in the file to \n!

When writing files, you should also be aware that \n will be translated to platform-dependent line endings.

Newline handling in different editors#

Vim#

When reading a file into the buffer, Vim will automatically detect the file format2. Then Vim will replace the platform-dependent newline characters with a special mark to mark the end of each line. When writing the buffer content back into the file, Vim will write the actual newline characters based on the detected file format.

For example, if you open a file with Windows-style line ending, Vim will replace all <CR><LF> with its own newline mark. If you try to search these two characters using their byte code (\%x0A for <CR> and \%x0D for <LF> ), you will find nothing. Neither can you find <CR> characters using \r in Windows file in Vim (suppose fileformats include dos). When searching in Vim, \n is used to specify end of line, no matter what the actual newline character is for this file. So you can search the line end with \n.

How do I show the <CR> characters in Vim then?#

You can open a Windows file in Vim and use e ++ff=unix3 to force Vim to treat this file as a unix file. Vim will then treat the \n characters as newline, thus removing it from the buffer. But the \r characters in the file will now be treated as normal characters and will be shown as ^M. You will see it now.

You can also press <Ctrl-V> and then press <Enter> to type a carriage return character. Then you can search this character using \r.

A pitfall in searching and replacing newlines#

In Vim, \n is used to represent newline only when you are searching it. If you want to represent a newline in replacement, use \r instead4. This makes no sense, but that is how Vim works.

Sublime Text#

According to discussions here, Sublime Text will also convert platform-dependent newline to \n in memory. When writing to files, it will write newlines based on the detected file type (Windows, Unix or Mac).

Notepad++#

Notepad++ is also a popular code editor. It can detect your line endings, but it will not replace the newline with \n. To show the newline characters in a file, go to View --> Show Symbol and toggle on option Show End of Line, you will be able to see the newline characters.

Conversion between different file formats?#

In Vim, you can use set ff=<Format> to covert the current file to desired format, where <Format> can be unix, dos or mac.

In Sublime Text, just choose the desired format from the bottom right status bar.

In Notepad++, go to Edit --> EOL Conversion and choose the desired file format.

There are also tools such as dos2unix and unix2dos which convert between different file formats.

References#


Title image is taken from here.