-3

Some background: Currently using Python3, was wondering if it was possible (so long as the file is in the same directory as the .py file) to open a file regardless of the file name and just go by file type? In my current program I want the user to be able to drop a file such as "test.pdf" and just have my program automatically recognize the .pdf and read that file in.

Any help would be greatly appreciated.

Damian
  • 11
  • 3

3 Answers3

0

You can use glob to list files in a directory using * notation

For example

In [6]: glob.glob('Downloads/*.pdf')
Out[6]:
['Downloads/file1.pdf',
 'Downloads/file2.pdf'

This will help you find the file as long as you know the extension (I used the Downloads folder to demonstrate how you can add a path to the query). You didn't articulate in the question if you could have more than one but that might be a case to watch out for

sedavidw
  • 11,116
  • 13
  • 61
  • 95
0

Use glob:

import glob

filelist = glob.glob("*.pdf")  # Get all pdf files in the current folder

for file in filelist:
    do_stuff(file)
frab
  • 1,162
  • 1
  • 4
  • 14
0

Please take a look at python os-listdir and python glob

But anyway:

import os

for file in os.listdir("."):
    if file.endswith("pdf"):
        print(file)
dor mordehcai
  • 102
  • 1
  • 1
  • 6