|
发表于 2017-8-12 16:34:57
|
显示全部楼层
本帖最后由 shinemic 于 2017-8-12 23:20 编辑
- # -*- coding: utf-8 -*-
- def delete_empty_line(file):
- filebuf = []
- with open(file, 'r+') as f:
- for line in f:
- if not line.isspace():
- filebuf.append(line)
- with open(file, 'w') as f:
- f.writelines(filebuf)
- def add_comma_after_each_line(file):
- filebuf = []
- append = ','
- with open(file, 'r+') as f:
- for line in f:
- filebuf.append(line[:-1] + append + '\n')
- with open(file, 'w') as f:
- f.writelines(filebuf)
- delete_empty_line('testfile')
- add_comma_after_each_line('testfile')
复制代码
测试(文件名为 testfile ):
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN">
- <plist version="1.0">
- <dict>
- <key>author</key>
- <string>Ihor Oleksandrov</string>
- <key>colorSpaceName</key>
- <string>boxy.ocean.dark</string>
- <string>0e709986-46a0-40a0-b3bf-c8dfe525c455</string>
- </dict>
- </plist>
复制代码
输出:
- <?xml version="1.0" encoding="UTF-8"?>,
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN">,
- <plist version="1.0">,
- <dict>,
- <key>author</key>,
- <string>Ihor Oleksandrov</string>,
- <key>colorSpaceName</key>,
- <string>boxy.ocean.dark</string>,
- <string>0e709986-46a0-40a0-b3bf-c8dfe525c455</string>,
- </dict>,
- </plist>,
复制代码
想法比较简单:- 对于删除空行,逐行读取文件,如果那一行是空的 (isspace),那么就跳过,仅读有内容的行,将这些读取的东西给filebuf,最后再将filebuf重新‘刷’进文件('w'模式打开)
- 对于增加逗号,原理同上,只需注意Python读文件的时候把换行统一处理成 '\n',所以写入filebuf的每行内容应为 「line[:-1] + ',' + '\n'」
更新
又有两种方案摘自网络:
- def new_strip_empty_lines(file):
- with open(file, 'r+') as f:
- text = '\n'.join([s for s in f.read().splitlines() if s.strip()])
- f.seek(0)
- f.write(text)
- def reg_delete_empty_lines(file):
- with open(file, 'r+') as f:
- out = filter(lambda x: not re.match(r'^\s*¥, x), f.read().splitlines())
复制代码
「注」将代码中的¥换为美元符号 |
|