使用Python删除以octothorpe开头的文件中的行?

drb*_*sen 14 python startswith

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

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

上面的代码似乎不起作用.有谁知道我的问题是什么?谢谢!

Ned*_*der 19

你没有写出第一行:

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

请记住enumerate(像大多数事情一样)从零开始.

更简洁(并且不重复输出行):

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


Dun*_*nes 6

我不打算在这里列举一下.你只需要它决定哪一行是第一行,哪一行不是.这应该很容易通过简单地写出第一行然后使用for循环有条件地写入不以'#'开头的其他行来处理.

def removeComments(inputFileName, outputFileName):

    input = open(inputFileName, "r")
    output = open(outputFileName, "w")

    output.write(input.readline())

    for line in input:
        if not line.lstrip().startswith("#"):
            output.write(line)

    input.close()
    output.close()
Run Code Online (Sandbox Code Playgroud)

感谢twopoint718指出使用lstrip的优势.