Shayna
Shayna

Reputation: 334

How would I exclude directories from os.listdir results?

I'm making a script that will encode files within a directory using b64/b16 and I'm using os.listdir to do so, but it also lists directories which causes problems since now it's trying to encode directories as if it were a file.

How would I be able to exclude directories from os.listdir results?

import os
import sys
import base64
import codecs
import time
import string
import glob

#C:\\Users\\Fedora\\Desktop\\Win 10
path = "C:\\Users\\Fedora\\Desktop\\Win 10"
dirs = os.listdir(path)
files = []
filecount = 0
fileprogress = 0
for file in dirs:
   files.append(file)
   filecount = filecount + 1

for x in files:
    os.system("cls")
    fileprogress = fileprogress + 1
    print("File " + str(fileprogress) + "/" + str(filecount))
    print("Encrypting " + x + "...")
    inputfile = open(path + "\\" + x, "rb")
    data = inputfile.read()
    inputfile.close()
    data = base64.b16encode(data)
    data = base64.b64encode(data)
    data = base64.b16encode(data)
    data = base64.b64encode(data)
    data = base64.b16encode(data)
    outputfile = open(path + "\\" + x + ".crypt", "wb")
    outputfile.write(data)
    outputfile.close()

Upvotes: 2

Views: 5162

Answers (3)

Eugene Morozov
Eugene Morozov

Reputation: 15836

You can use os.path.isdir function to check if the current file is a directory.

Also, it is much better to use string formatting operations instead of string concatenation: not

print("File " + str(fileprogress) + "/" + str(filecount))

but

print("File {}/{}".format(fileprogress, filecount))

Such code is much easier to understand and modify.

Upvotes: 1

Skycc
Skycc

Reputation: 3555

use filter

filepath = "C:\\Users\\Fedora\\Desktop\\Win 10"
dirs = os.listdir(path)
files = filter(lambda x:os.path.isfile(os.path.join(filepath, x)), dirs)

or list comprehension with os.path.isfile()

filepath = "C:\\Users\\Fedora\\Desktop\\Win 10"
dirs = os.listdir(path)
files = [x for x in dirs if os.path.isfile(os.path.join(filepath, x))]

Upvotes: 4

Yaron
Yaron

Reputation: 10450

Instead of using os.listdir() your can use os.walk which will return separate list for files and directories

python-oswalk-example

import os

path = "C:\\Users\\Fedora\\Desktop\\Win 10"

for (path, dirs, files) in os.walk(path):
    print path
    print dirs
    print files

pythoncentral os-walk

#Import the os module, for the os.walk function
import os

#Set the directory you want to start from
path = "C:\\Users\\Fedora\\Desktop\\Win 10"
for dirName, subdirList, fileList in os.walk(path):
    print('Found directory: %s' % dirName)
    for fname in fileList:
        print('\t%s' % fname)

Upvotes: 1

Related Questions