简体   繁体   中英

Unexpected output while iterating over list

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?

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.

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") 

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")

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.

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