'How to ignore files that start with '.' and print the rest?
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
Solution 1:[1]
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.
Solution 2:[2]
#Creates empty list
files_no_period = [
]
if 'a' not in flags:
for file in file_list:
if not files.startswith('.'):
files_no_period.append(file)
#Prints files in list
print ("\n".join(files_no_period))
"""
- Changed 'for files' to 'for file', just because you are going through each file on at a time.
- Changed if statement to if not, meaning if file isn't starting with a '.'.
- Add each file that doesn't start with '.' to a list.
- List all files from the list of files that don't start with a '.'.
"""
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Kovy Jacob |
