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():"
- it works but it works from the directory where you start the program. The path to the directory that I enter is correct because I did a print(items) before the for loop, and the files and folders are listed. When I tried debugging it seems that the if statement always returns False - don't know why. In Linux environment it worked for some directories that I tried, but not for all.
What am I doing wrong? Thanks.
CodePudding user response:
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']
CodePudding user response:
your code is correct. does enter_dir is something like "/home/username/.../"? if not, program can work incorrect