python3 读写文件换行符的方法

作者:zhouguoqionghai 时间:2021-09-29 11:21:22 

最近在处理文本文件时,遇到编码格式和换行符的问题。

基本上都是GBK 和 UTF-8 编码的文本文件,但是python3 中默认的都是按照 utf-8 来打开。用不正确的编码参数打开,在读取内容时,会抛出异常。


open(dirpath + "\\" + file, mode = "r+", encoding = "gbk", newline = "")

捕获抛出的异常,关闭文件。使用另外一种编码格式打开文件再重新读取。

读取文件时,

newline参数用来指定读取时,对换行符的处理。缺省为 None,表示通用的换行符(“\n”),即文件的换行符是啥,读出来都是 “\n”.

newline = "" 表示读取的换行符保持不变,原来是啥,读出来还是啥。

newline = “\n” 表示遇到 "\n" 才一行结束,“\r” 像其他普通字符一样对待。

newline = “\r” 表示遇到 "\r" 才一行结束,“\n” 像其他普通字符一样对待。

在文件写入时,

newline = None时,写入的“\n” 自动都变为系统默认的换行符。所以 “\r\n” 在windows下会变成“\r\r\n”写入。

newline = "" 表示不做任何转换写入。

newline = “\n” 表示不做任何转换写入。

newline = “\r” 表示将 “\n” 和 "\r" 都当做 "\r" 进行写入,所以“\r\n” 会变成 “\r\r”进行写入。

案例:将源码下的所有makefile 文件中的 -c 参数前,加上 -g 选项。


import os
import re
os.chdir(r"E:\code")
s = os.walk(".")
pattern = re.compile(r"\s-c\s")
for dirpath, dirnames, filenames in s:
for file in filenames:
if file.endswith(".mak") or "makefile" in file: #部分以 .mak 结尾,部分以makefile命名
print(file)
with open(dirpath + "\\" + file, mode = "r+", encoding = "gbk", newline = "") as f: #newline为空串表示换行符不转换
try: #编码问题造成的异常
lines = f.readlines() #一次读取所有的行到内存
f.seek(0)    #回到文件起始处
for line in lines:
#newline = line.replace(" -c "," -g -c ")
newline= re.sub(pattern, " -g -c ", line)
f.write(newline)
except ValueError:
f.close()
with open(dirpath + "\\" + file, mode = "r+", encoding = "utf-8", newline = "") as fnew:
try:
lines = fnew.readlines()
fnew.seek(0)    
for line in lines:
#newline = line.replace(" -c "," -g -c ")
newline= re.sub(pattern, " -g -c ", line)
fnew.write(newline)
except ValueError:
print("*************** " + dirpath + "\\" + file) #打印utf-8 和 gbk 之外编码的文件名

来源:https://blog.csdn.net/zhouguoqionghai/article/details/60879794

标签:python,读写,文件,换行符
0
投稿

猜你喜欢

  • Flask项目的部署的实现步骤

    2023-08-11 17:59:58
  • PHP封装CURL扩展类实例

    2023-07-17 15:19:50
  • ASP 千万级数据分页的存储过程

    2011-04-14 11:08:00
  • PHP 实现一种多文件上传的方法

    2024-05-03 15:07:11
  • 详解 Go 语言中 Map 类型和 Slice 类型的传递

    2024-05-29 22:07:11
  • Python实现监控程序执行时间并将其写入日志的方法

    2023-01-15 01:35:53
  • Appium自动化测试中获取Toast信息操作

    2022-05-12 07:10:48
  • 使用Python实现企业微信的自动打卡功能

    2021-02-27 02:41:34
  • asp中的rs.open与conn.execute的区别说明

    2011-02-24 10:56:00
  • Python+matplotlib实现堆叠图的绘制

    2023-07-21 17:38:35
  • Python-OpenCV教程之图像的位运算详解

    2022-10-17 23:44:43
  • 在python中使用xlrd获取合并单元格的方法

    2023-09-09 17:00:43
  • python解析xml文件实例分析

    2021-02-17 03:25:18
  • python并发场景锁的使用方法

    2022-12-30 17:25:20
  • 使用Python实现控制摄像头的方法详解

    2023-01-15 14:38:12
  • Python 硬币兑换问题

    2022-04-03 06:30:09
  • 解决python彩色螺旋线绘制引发的问题

    2023-06-30 12:49:12
  • Golang信号处理及如何实现进程的优雅退出详解

    2024-05-28 15:24:29
  • bootstrapValidator bootstrap-select验证不可用的解决办法

    2024-04-10 13:53:06
  • Python中最好用的命令行参数解析工具(argparse)

    2022-12-30 06:34:31
  • asp之家 网络编程 m.aspxhome.com