0

Having some trouble getting a list of files from a user defined directory. The following code works fine:

inputdirectory = r'C:/test/files'
inputfileextensions = 'txt'
files = glob.glob(inputdirectory+"*."+inputfileextensions)

But I want to allow the user to type in the location. I've tried the following code:

inputdirectory = input("Please type in the full path of the folder containing your files:    ")
inputfileextensions = input("Please type in the file extension of your files:    ")
files = glob.glob(inputdirectory+"*."+inputfileextensions)

But it doesn't work. No error message occurs, but files returns as empty. I've tried typing in the directory with quotes, with forward and backward slashes but can't get it to work. I've also tried converting the input to raw string using 'r' but maybe by syntax is wrong. Any ideas?

Actuary
  • 129
  • 4
  • 9

3 Answers3

1

Try to join path with os.path.join. It will handle slash issue.

import os
...
files = glob.glob(os.path.join(inputdirectory, "*."+inputfileextensions))
Alperen
  • 2,495
  • 1
  • 17
  • 33
1

Not quite sure how the first version works for you. The way the variables are defined, you should have the input to glob as something like:

inputdirectory+"*."+inputfileextensions == "C:\test\files*.txt"

Looking at the above value you can realize that its not something that you are trying to achieve. Instead, you need to join the two paths using the backslash operator. Something like:

os.path.join(inputdirectory, "*."+inputfileextensions) == "C:\test\files\*.txt"

With this change, the code should work regardless of whether the input is taken from the user or predefined.

-1

Working code for sample, with recursive search.

#!/usr/bin/python3

import glob
import os

dirname = input("What is dir name to search files? ")
path = os.path.join(dirname,"**")
for x in glob.glob(path, recursive=True):
    print(x)
ukki
  • 45
  • 6