2015-11-04 71 views
-3
def codeOnly (file): 
    '''Opens a file and prints the content excluding anything with a hash in it''' 
    f = open('boring.txt','r') 
    codecontent = f.read() 

    print(codecontent) 
codeOnly('boring.txt') 

我想打开这个文件并打印它的内容,但是我不想打印任何带有散列的行。是否有防止这些行被打印的功能?如何删除从被印刷有一定的条件下一个文件行?

+1

欢迎堆栈溢出!你似乎在要求某人为你写一些代码。堆栈溢出是一个问答网站,而不是代码写入服务。请[see here](http://stackoverflow.com/help/how-to-ask)学习如何编写有效的问题。 –

+1

...检查是否有一个哈希在它在打印前?为什么会有一个完整的功能呢?! – jonrsharpe

+0

你不是真的想从文件中删除行,只是没有打印出来,对不对? – martineau

回答

1

与打印下面的脚本不包含所有行一#

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') 

使用with将确保该文件将自动关闭之后。

0

可以检查线路包含哈希与not '#' in codecontent(使用in):

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') 

如果你真的想保持唯一的代码行,你可能要保持线路的一部分,直到哈希,因为在语言如Python,你可以哈希之前有代码,例如:

print("test") # comments 

您可以找到index

for line in f: 
    try: 
     i = line.index('#') 
     line = line[:i] 
    except ValueError: 
     pass # don't change line 

现在每个线将不包含从文本和包括散列标签,直到行的末尾。一行中第一个位置的散列标签会产生一个空字符串,你可能想要处理它。

+2

如果该文件包含的任何'“#”'字符这不会打印出任何东西,不只是省略有他们的线。 – martineau

+0

是的,你说得对,修好了。 – agold

相关问题