Reputation: 15
I am trying to print the file names in my directory using the following code:
dir_path = 'D:/#/#/#/#.json'
for filename in os.listdir(dir_path):
print filename
f = open(os.path.join(dir_path,filename), 'r')
but this error is displayed when running the code:
for filename in os.listdir(dir_path):
WindowsError: [Error 267] The directory name is invalid: 'D:/#/#/#/#.json/*.*'
I am unsure what the json/*.*
means in the error message, I am new to Python so apologies if this question is vague.
Upvotes: 0
Views: 6933
Reputation: 64949
Your question is unclear as to whether the directory D:/#/#/#
contains any files in it other than JSON files, so I shall give two answers. Hopefully one of them will apply to you:
Directory contains only JSON files
In that case, simply remove the /#.json
from the end of dir_path
:
dir_path = 'D:/#/#/#'
for filename in os.listdir(dir_path):
print filename
f = open(os.path.join(dir_path,filename), 'r')
Directory contains JSON files and other files that you want to exclude
In this situation it's best to use the Python glob
module.
The following should list all of the .json
files in the folder D:/#/#/#
:
import glob
dir_path = 'D:/#/#/#/*.json'
for filename in glob.glob(dir_path):
print filename
f = open(filename, 'r')
Note that filenames returned by glob.glob
include the directory path, so we don't use os.path.join
on them.
os.listdir
lists all files in the directory you give it. However it seems you're not passing it the name of a directory, you're passing it the name of a file. How can it possibly list all the files in a directory if you don't give it a directory?
Upvotes: 1