Reputation: 106
I am printing the files name from current directory in my os . files in my current directory are :test.py,Bob.txt,Alice.txt,
import os
files=os.listdir('.')
print(files)
#['test.py','Bob.txt','Alice.txt']
for file in files:
if file.endswith(".txt"):
print(file)
else:
print(".txt no such file in this directory")
break
I am getting output ".txt no such file in this directory"
but it should be print files name Bob.txt and Alice.txt please explain why and how?
Upvotes: 0
Views: 68
Reputation: 647
If you wanted to check for .txt
file recursively in the all the subdirectories then you can use os.walk
import os
path_of_directory = "."
flag = False
for directory, dir_names, files_in_dir in os.walk(path_of_directory):
for each_file in files_in_dir:
if os.path.splitext(each_file)[-1] == ".txt":
print(each_file)
flag = True
if not flag:
print("No .txt file")
Upvotes: 1
Reputation: 77337
The if/else is run for each file in the list. As soon as you hit a non txt file, the else clause runs, prints the unwanted message and breaks out of the loop. Instead, you could track whether you've seen a txt file and print afterwards
import os
files=os.listdir('.')
print(files)
has_txt = False
for file in files:
if file.endswith(".txt"):
has_txt = True
print(file)
if not has_txt:
print(".txt no such file in this directory")
But I think a list comprension to filter the directory list is the way to go.
import os
txt_files = [name for name in os.listdir('.') if name.endswith(".txt")]
if txt_files:
print("\n".join(txt_files))
else:
print(".txt no such file in this directory")
Upvotes: 1
Reputation: 209
With how you currently have your code structured, it will go to the else statement as soon as it encounters a single file that doesn't end with .txt
. Since it seems like you want files that do end with .txt
, it is possible to use list comprehension to quickly filter through the list.
txtfiles = [file for file in files if file.endswith(".txt")]
if len(txtfiles) > 0:
for file in txtfiles:
print(file)
else:
print(".txt no such file in this directory")
An alternative is to do the filtering manually within a for loop, only checking for an empty list at the end.
Upvotes: 1
Reputation: 139
Take a look for loop examples.
The problem is break
ends the loop
for file in files:
if file.endswith(".txt"):
print(file)
else:
print(".txt no such file in this directory")
break
While it iterates the loop the first item is test.py
It does not match .endswith(".txt")
, remove the break
should work.
Upvotes: 0