NewtoTheCrew
NewtoTheCrew

Reputation: 31

os.listdir not listing files in directory

For some reason os.listdir isn't working for me. I have 6 .xlsx files inside the input_dir but it creating a list with nothing in it instead of showing a list of 6 files. If I move the .xlsx files into where the script is one directory back, and update the input_dir path it then finds all 6 files but I need the 6 files to be one directory up in their own folder. And when I move them one directory up into their own folder, and I update the input_dir path it doesn't find them at all.

import openpyxl as xl 
import os
import pandas as pd
import xlsxwriter

input_dir='C:\\Users\\work\\comparison'

files = [file for file in os.listdir(input_dir)
         if os.path.isfile(file) and file.endswith(".xlsx")]


for file in files: 
   input_file =  os.path.join(input_dir, file)
   wb1=xl.load_workbook(input_file)
   ws1=wb1.worksheets[0]

Upvotes: 1

Views: 4195

Answers (2)

RandomGuy
RandomGuy

Reputation: 1197

The problem comes from os.path.isfile(file) : os.listdir(input_dir) returns a list of filenames inside the input_dir directory, but without their path. Hence your error, as os.path.isfile(file) will look into your current directory, which obviously doesn't have any of those filenames.

You can easily correct this by simply changing os.path.isfile(input_dir + '\\' + file), but a prettier solution would rather be to simply delete this part of the code (as if os.listdir returns this filename, then it is necessary into your directory and there's no need to check if so) :

files = [file for file in os.listdir(input_dir) if file.endswith(".xlsx")]

Upvotes: 0

Rion DMello
Rion DMello

Reputation: 81

When you move the files into input_dir, the following line creates an empty list:

files = [file for file in os.listdir(input_dir)
         if os.path.isfile(file) and file.endswith(".xlsx")]

This is because you are checking for os.path.isfile(file) instead of os.path.isfile(os.path.join(input_dir, file))

When files are present in the same directory as the script, it's able to find the file and creates the list correctly.

Alternatively, you could try using glob.glob which accepts a file path pattern and returns full path to the file in the iterator.

Upvotes: 1

Related Questions