简体   繁体   中英

How to remove lines from a file that is being printed with certain conditions?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM