Reputation: 27
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
Upvotes: 1
Views: 1032
Reputation: 1119
#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 '.'.
"""
Upvotes: 0
Reputation: 41281
A handful of options are available:
if 'a' not in flags:
for files in file_list:
if not files.startswith('.'):
print(files)
if 'a' not in flags:
for files in file_list:
if files.startswith('.'):
continue
print(files)
for files in file_list:
if 'a' in flags or (not files.startswith('.')):
print(files)
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.
Upvotes: 2