python3 读写文件换行符
来源:互联网 发布:梦幻口袋版炼兽笼数据 编辑:程序博客网 时间:2024/05/08 16:11
最近在处理文本文件时,遇到编码格式和换行符的问题。
基本上都是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 osimport reos.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 之外编码的文件名
0 0
- python3 读写文件换行符
- Java文件读写 & 输出换行符
- python3-读写文件
- python3 文件读写
- Python3 中文文件读写
- python3学习--文件读写
- python3--文件读写1
- Python3读写csv文件
- python文件读写换行问题
- python3 文件读写(2)
- python3的文件读写模式
- Python文件读写时的换行符与回车符
- Python文件读写时的换行符与回车符
- Java简单的文件读写,换行
- 文件的换行及读写中文
- python3调用COM读写excel文件
- Python3.2官方文档翻译--文件读写
- Python3之文件读写操作详解
- 手把手教你用Mysql-Cluster-7.5搭建数据库集群
- 火热网络框架Retrofit的介绍
- 类与对象
- Android TimeLine 时间节点轴的实现
- WebView详解
- python3 读写文件换行符
- C# 定时器
- js 清除浏览器缓存方法
- LeetCode 2. Add Two Numbers 题解
- jstl
- 常见网页状态码
- Merge Sorted Array
- 逻辑斯蒂回归和决策树
- 【九度OJ】题目1442:A sequence of numbers 解题报告