鱼C论坛

 找回密码
 立即注册
查看: 1844|回复: 2

文件操作中遇到的问题

[复制链接]
发表于 2017-8-12 15:53:44 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
问题1:如何在文件中查找空白的行,并删除空白的行。
问题2:如何在每一行后面添加一个逗号“,”
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 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())
「注」将代码中的¥换为美元符号
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-8-12 23:12:32 | 显示全部楼层
非常感谢大神。您的回复给我非常大的帮助,并且学到了很多东西
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-2-24 11:27

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表