Python:如何在读取文件时忽略#comment行 [英] Python: How to ignore #comment lines when reading in a file

查看:1853
本文介绍了Python:如何在读取文件时忽略#comment行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我刚刚读取一个行形式的文本文件,我想知道如何编写代码以忽略带有一个散列#的开头的行。

In Python, I have just read a line form a text file and I'd like to know how to code to ignore comments with a hash # at the beginning of the line.

我认为应该是这样的:

for 
   if line !contain #
      then ...process line
   else end for loop 

但我是新的到Python,我不知道语法

But I'm new to Python and I don't know the syntax

推荐答案

,您可以使用 startswith()

例如

for line in open("file"):
    li=line.strip()
    if not li.startswith("#"):
        print line.rstrip()

这篇关于Python:如何在读取文件时忽略#comment行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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