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

I want to open this file and print the contents of it however i don't want to print any lines with hashes in them. Is there a function to prevent these lines from being printed?

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
Flatend
  • 3
  • 2
  • 1
    Welcome to Stack Overflow! You seem to be asking for someone to write some code for you. Stack Overflow is a question and answer site, not a code-writing service. Please [see here](http://stackoverflow.com/help/how-to-ask) to learn how to write effective questions. – Morgan Thrapp Nov 04 '15 at 16:17
  • 1
    ...check if there's a hash in it before you print it? Why would there be a whole function just for that?! – jonrsharpe Nov 04 '15 at 16:17
  • You don't really want to remove the lines from the file, just not print them, correct? – martineau Nov 04 '15 at 16:33

2 Answers2

1

The following script with print all lines which do not contain a #:

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

Using with will ensure that the file is automatically closed afterwards.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
0

You can check if the line contains a hash with not '#' in codecontent (using 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')

If you really want to keep only code lines, you might want to keep the part of the line until the hash, because in languages such as python you could have code before the hash, for example:

print("test")  # comments

You can find the index

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

Now each of your lines will contain no text from and including the hash tag until the end of the line. Hash tags in the first position of a line will result in an empty string, you might want to handle that.

Community
  • 1
  • 1
agold
  • 6,140
  • 9
  • 38
  • 54
  • 2
    This won't print anything if the file contains any `'#'` characters, not just omit the lines that have them. – martineau Nov 04 '15 at 16:30