w3resource

Python: Find files and skip directories of a given directory

Python Basic: Exercise-136 with Solution

Write a Python program to find files and skip directories of a given directory.

Sample Solution-1:

Python Code:

import os
print([f for f in os.listdir('/home/students') if os.path.isfile(os.path.join('/home/students', f))])

Sample Output:

['test.txt', '.mysql_history', '.bash_logout', '.bash_history', '.profile', 'abc.py', '.viminfo', 'mynewtest.t
xt', 'myfile.txt', 'logging_example.out', '.web-term.json', 'abc.txt', '64a57280-272f-11e7-9ce4-832a8e030fef.p
y', 'exercise.cs', '.bashrc', 'Example.cs', 'myfig.png', 'file.out', 'line.gif', 'mmm.txt\n', 'temp.txt', 'ddd
d.txt\n', 'sss.dat\n', 'result.txt', 'output.jpg', '26492-1274250701.png', 'mytest.txt'] 

Sample Solution-2:

Python Code:

import os
user_path = 'd:/'
for fname in os.listdir(user_path):
   path = os.path.join(user_path, fname)
   if os.path.isdir(path):
       # skip directories
       continue
   # print the file names
   print(fname)

Sample Output:

5C90A0D8.tmp
abcd.txt
BMCASSET.zip
computer.png
Dreamweaver 8.zip
Dreamweaver8-en.zip
eula.1028.txt
eula.1031.txt
eula.1033.txt
eula.1036.txt
eula.1040.txt
eula.1041.txt
eula.1042.txt
eula.2052.txt
eula.3082.txt
ezgif.com-gif-maker.png
globdata.ini
How To Use Sets in Python (Python Tutorial .mp4
hr
index.html
install.exe
install.ini
install.res.1028.dll
install.res.1031.dll
install.res.1033.dll
install.res.1036.dll
install.res.1040.dll
install.res.1041.dll
install.res.1042.dll
install.res.2052.dll
install.res.3082.dll
java-array-exercise-flowchart-35.png
LICENSE
Local Disk (C) - Shortcut.lnk
Main.java
math_expression_commands.txt
msdia80.dll
pandas-series-loc-7 (2).zip
psr (Autosaved).xlsx
psr.xlsx
script.js
share-mutualfund.xlsx
sqlite3.def
sqlite3.dll
vcredist.bmp
VC_RED.cab
VC_RED.MSI
visustin.txt
w3resource-logo.png

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to print a variable without spaces between values.
Next: Write a Python program to extract single key-value pair of a dictionary in variables.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Unpack variables from iterable:

# One can unpack all iterables (tuples, list etc)
>>> a, b, c = 1, 2, 3
>>> a, b, c
(1, 2, 3)

>>> a, b, c = [1, 2, 3]
>>> a, b, c
(1, 2, 3)