Python写入Shell文件使用Linux系统的换行符

在 Python 中向文本文件写入内容时,换行符的处理与打开文件的 newline 参数有关。

Linux 系统的换行符就是 \n(LF),如果你希望写入的文件在任何操作系统下都使用 \n 换行 (包括在 Windows 上运行时),可以在 open() 中指定 newline='\n'

代码

python 复制代码
with open('output.txt', 'w', newline='\n', encoding='utf-8') as f:
    f.write('第一行\n第二行\n第三行')

配合 print 写入时也保持 \n

print 默认会在末尾添加 os.linesep,在 Windows 下仍然是 \r\n。只需在打开文件时同样设置 newline='\n',然后指定 end='\n' 即可:

python 复制代码
with open('output.txt', 'w', newline='\n', encoding='utf-8') as f:
    print('第一行', file=f, end='\n')
    print('第二行', file=f, end='\n')
相关推荐
用户8356290780511 天前
Python 实现 PDF 文件加密与解密方法
后端·python
用户8356290780511 天前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生1 天前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师1 天前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码1 天前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf1 天前
FastAPI 如何连接 MySQL
后端·python
orion572 天前
Missing Semester Class1:course overview and introduction of shell
linux
apocelipes2 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780512 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
用户120487221612 天前
Linux驱动编译与加载
linux·嵌入式