使用Python删除以octothorpe开头的文件中的行吗? [英] Use Python to remove lines in a files that start with an octothorpe?

查看:337
本文介绍了使用Python删除以octothorpe开头的文件中的行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个直截了当的问题,但我似乎无法指出我的问题.我正在尝试删除文件中以八丁(#)开头的所有行,但第一行除外.这是我正在使用的循环:

This seems like a straight-forward question but I can't seem to pinpoint my problem. I am trying to delete all lines in a file that start with an octothorpe (#) except the first line. Here is the loop I am working with:

for i, line in enumerate(input_file):
    if i > 1:
        if not line.startswith('#'):
            output.write(line)

上面的代码似乎无效.有谁知道我的问题是什么?谢谢!

The above code doesn't seem to work. Does anyone known what my problem is? Thanks!

推荐答案

您没有写出第一行:

for i, line in enumerate(input_file):
    if i == 0:
        output.write(line)
    else:
        if not line.startswith('#'):
            output.write(line)

还请记住,enumerate(就像大多数事物一样)从零开始.

Keep in mind also that enumerate (like most things) starts at zero.

更加简洁(不要重复输出行):

A little more concisely (and not repeating the output line):

for i, line in enumerate(input_file):
    if i == 0 or not line.startswith('#'):
        output.write(line)

这篇关于使用Python删除以octothorpe开头的文件中的行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆