Home > Back-end >  How to ignore files that start with '.' and print the rest?
How to ignore files that start with '.' and print the rest?

Time:02-20

Hi everyone I'm working on a school project where we are writing code to implement our own built unix shell in python. I'm stuck on this small part with the ls -a command where I want to ignore the .(dot) files. This is the code I have, I'm not sure how to finish it.

  if 'a' not in flags:
    for files in file_list:
      if files.startswith('.'):
        #ignore . files

CodePudding user response:

A handful of options are available:

  • Invert the condition:
    if 'a' not in flags:
      for files in file_list:
        if not files.startswith('.'):
          print(files)
    
  • Continue the loop without printing if the file matches:
    if 'a' not in flags:
      for files in file_list:
        if files.startswith('.'):
          continue
        print(files)
    
  • Combine the two conditions together to make the code less nested
    for files in file_list:
      if 'a' in flags or (not files.startswith('.')):
        print(files)
    
  • Separate filtering from iteration:
    if 'a' not in flags:
      file_list = [files for files in file_list if not files.startswith('.')
    # more if-statements to process other flags of interest, 
    # e.g. if a flag for sorting is specified, sort the files
    for files in file_list:
       print(files)
    

I would lean toward the first option in the simplest case, or the last option if you need extensible logic that scales to more flags. I used a list comprehension for shorthand, but you can also call a function that handles the list, write a handwritten loop that updates the file list, or something else.

I would also add the nit that the variable which you call files refers to a single file at a time, so it should be named file (or if there's ambiguity between file names and file objects, perhaps file_name). I've left it as-is in the answer for consistency with your existing code.

CodePudding user response:

for files in file_list:
  if files.startswith('.dot'):
    continue
for files in file_list:
  if not files.startswith('.dot'):
    do_something()
for files in file_list:
  if files.startswith('.dot'):
    pass
  • Related