Pitar Hetar
Pitar Hetar

Reputation: 13

Python basic - os library issue - os.path.isfile() not working as expected

I tried to make a small python program that lists the files and folders in a directory, then adds the files into a file list and the directories into directory list. What I wrote:

import os

list_files = []
list_dir = []

enter_dir = input('Enter dir to list its content: ')

for items in os.listdir(enter_dir):
    if os.path.isfile(items):
        list_files.append(items)
    elif os.path.isdir(items):
        list_dir.append(items)
print(f'{enter_dir} has the following files: {list_files}')
print(f'{enter_dir} has the following directories: {list_dir}')

it is not working and the lists are empty when I print them, funny thing when you don't enter a directory and leave it like "for items in os.listdir():"

What am I doing wrong? Thanks.

Upvotes: 1

Views: 52

Answers (1)

Maurice Meyer
Maurice Meyer

Reputation: 18106

os.listdir returns the names of files and directories, not the full path. You need to create the full path your self using os.path.join:

import os

list_files = []
list_dir = []

enter_dir = input('Enter dir to list its content: ')

for item in os.listdir(enter_dir):
    fullItemPath = os.path.join(enter_dir, item)
    if os.path.isfile(fullItemPath):
        list_files.append(fullItemPath)
    elif os.path.isdir(fullItemPath):
        list_dir.append(fullItemPath)
print(f'{enter_dir} has the following files: {list_files}')
print(f'{enter_dir} has the following directories: {list_dir}')

Output (on Mac):

python /tmp/y.py
Enter dir to list its content: /Users
/Users has the following files: ['/Users/.localized']
/Users has the following directories: ['/Users/xxx', '/Users/Shared']

Upvotes: 1

Related Questions