Python 包含汉字的文件读写之每行末尾加上特定字符
作者:清穆2013 时间:2022-02-01 13:13:46
最近,接手的项目里,提供的数据文件格式简直让人看不下去,使用pandas打不开,一直是io error.仔细查看,发现文件中很多行数据是以"结尾,然而其他行缺失,因而需求也就很明显了:判断每行的结尾是否有",没有的话,加上就好了。
采用倒叙的方式好了,毕竟很多人需要的只是一个快速的解决方案,而不是一个why. 解决方案如下:
b = open('b_file.txt', w)
with open('a_file.txt', 'r') as lines:
for line in lines:
line = line.strip()
if not line.endswith(r'"'):
line += r'"'
line += '\n'
b.write(line)
b.close()
a.close()
其中整个过程的关键在于
line = line.strip()
之前我偷懒,直接使用省去了上面那行,结果在判断条件栽了跟头,程序认为每一行都不是以"结尾:
if not line.endswith(r'"')
硬着头皮试上去,重写:
for line in open(data_path+'heheda.txt', 'r'):
if not line[-2] == r'"':
print line
line = line[:-1] + r'"' + line[-1:]
print line
此时判断条件为 if not line[-2] == r'"'
,这样才能得到除最后一行之外的正确结果。众所周知的原因,在windows系统中,文件的回车符是"\r\n",因而,在没有strip()处理好回车符的时候,需要手动在每一行的结尾前移一个字节进行判断每行的末尾。而对于文件的最后一行,一般情况下不是回车符作为结尾,毕竟不要换行了嘛。因而line[-2]则定位到了最后一个汉字的中间,将\xx\xx,硬写成了\xx"\xx,使得最后一个字显示错误。
以上所述是小编给大家介绍的Python 包含汉字的文件读写之每行末尾加上特定字符网站的支持!
来源:http://www.cnblogs.com/QM-12/archive/2016/12/12/6163810.html
标签:python,文件读写,字符
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现ID3决策树算法
2023-04-13 09:35:28
Python __all__变量用法示例详解
2023-05-13 01:40:11
Python图像处理之图像金字塔详解
2022-03-11 10:35:04
![](https://img.aspxhome.com/file/2023/2/107512_0s.png)
支持png透明图片的php生成缩略图类分享
2023-11-18 07:26:13
![](https://img.aspxhome.com/file/2023/5/104175_0s.jpg)
谈一谈基于python的面向对象编程基础
2021-09-09 11:04:39
![](https://img.aspxhome.com/file/2023/3/63543_0s.png)
Python实现对中文文本分段分句
2022-09-16 18:16:50
python实现Zabbix-API监控
2022-04-23 17:41:00
![](https://img.aspxhome.com/file/2023/5/71505_0s.jpg)
python list转置和前后反转的例子
2022-04-26 10:39:55
![](https://img.aspxhome.com/file/2023/9/81719_0s.jpg)
pandas 实现将重复表格去重,并重新转换为表格的方法
2023-09-09 05:26:58
Python利用机器学习算法实现垃圾邮件的识别
2021-02-24 04:31:04
![](https://img.aspxhome.com/file/2023/5/107015_0s.jpg)
解析Oracle 8i/9i的计划稳定性
2010-07-26 13:09:00
使用Python脚本将绝对url替换为相对url的教程
2022-09-03 09:36:39
全面理解Python中self的用法
2022-10-09 07:16:50
发布你的Python模块详解
2021-06-10 02:03:53
Python3 循环语句(for、while、break、range等)
2022-11-26 14:36:40
![](https://img.aspxhome.com/file/2023/5/128315_0s.png)
Python入门教程(七)Python数字类型
2022-05-29 22:40:00
![](https://img.aspxhome.com/file/2023/3/81523_0s.png)
Python中免验证跳转到内容页的实例代码
2021-03-27 11:19:55
![](https://img.aspxhome.com/file/2023/8/99478_0s.png)
5.PHP的其他功能
2023-11-14 16:45:42
简单说明Python中的装饰器的用法
2022-01-30 21:57:32
![](https://img.aspxhome.com/file/2023/8/89428_0s.png)
功能和外观都还不错的js版幻灯片效果
2007-08-05 12:20:00