Python 如何从带有特定条件的打印文件中删除行?

Python 如何从带有特定条件的打印文件中删除行?,python,python-3.x,Python,Python 3.x,我想打开这个文件并打印它的内容,但是我不想打印任何带有哈希的行。是否有防止打印这些行的功能?您可以检查该行是否包含codecontent中带有而不是“#”的哈希(使用): 如果您真的只想保留代码行,您可能希望保留行的一部分直到散列,因为在python等语言中,可以在散列之前保留代码,例如: def codeOnly (file): '''Opens a file and prints the content excluding anything with a hash in it'''

我想打开这个文件并打印它的内容,但是我不想打印任何带有哈希的行。是否有防止打印这些行的功能?

您可以检查该行是否包含codecontent中带有
而不是“#”的哈希(使用):

如果您真的只想保留代码行,您可能希望保留行的一部分直到散列,因为在python等语言中,可以在散列之前保留代码,例如:

def codeOnly (file):
    '''Opens a file and prints the content excluding anything with a hash in it'''
    f = open('boring.txt','r')
    for line in f:    
       if not '#' in line:
          print(line)
codeOnly('boring.txt')
你可以找到


现在,在每一行结束之前,您的每一行都不包含来自或包括哈希标记的文本。行的第一个位置的哈希标记将导致空字符串,您可能需要处理该问题。

以下脚本将打印所有不包含
#
的行:


一起使用将确保文件在之后自动关闭。

欢迎使用堆栈溢出!您似乎在要求某人为您编写一些代码。堆栈溢出是一个问答网站,而不是代码编写服务。请学习如何写有效的问题…打印前检查其中是否有散列?为什么会有一个完整的功能就为了这个?!您不想从文件中删除行,只是不打印行,对吗?如果文件包含任何
“#”
字符,则不会打印任何内容,而不仅仅是忽略包含这些字符的行。
def codeOnly (file):
    '''Opens a file and prints the content excluding anything with a hash in it'''
    f = open('boring.txt','r')
    for line in f:    
       if not '#' in line:
          print(line)
codeOnly('boring.txt')
print("test")  # comments
for line in f:
   try:
      i = line.index('#')
      line = line[:i]
   except ValueError:
      pass # don't change line
def codeOnly(file):
    '''Opens a file and prints the content excluding anything with a hash in it'''
    with open(file, 'r') as f_input:
        for line in f_input:
            if '#' not in line:
                print(line, end='')

codeOnly('boring.txt')