1

I am trying to open a file using the full path, but I don't know the complete name of the file, just a unique string within it.

i = identifier
doc = open(r'C:\my\path\*{0}*.txt'.format(i), 'r')

Now obviously this doesn't work because I'm trying to use the wildcard along with the raw string. I have had a lot of trouble in the past trying to use file paths without preceding them with 'r', so I'm not sure of the best way to handle the incomplete file name. Should I just forget raw string notation and use '\\\\' for the file path?

3
  • docs.python.org/2/library/glob.html is the best way to look up filenames that you don't know - open doesn't work with wildcards. Also, the best way to work with the backslashes in your DOS pathnames is to use os.path.join to build the path. Commented Nov 27, 2013 at 20:44
  • @PeterDeGlopper What if I just do path=glob.glob(r'path/*identifier*.txt') then doc=open(path, 'r')? Commented Nov 27, 2013 at 20:50
  • glob.glob returns a possibly empty list, so you can't directly open its return value. But paths=glob.glob(...); if paths: doc = open(paths[0], 'r') is basically right. It appears that glob is forgiving about which file dividers you use. Commented Nov 27, 2013 at 20:59

2 Answers 2

2

From the question comments:

import glob
import os

i = "identifier"
basePath = r"C:\my\path"

filePaths = glob.glob(os.path.join(basePath,'*{0}*.txt'.format(i)))

# Just open first ocurrence, if any
if filePaths:
    print "Found: ", filePaths[0]
    doc = open(filePaths[0], 'r')
Sign up to request clarification or add additional context in comments.

Comments

0
import os 
    
def foo(path):
    _, _, files = next(os.walk(path))
    print(files)
    
files = foo(r'C:\Users') 
files[1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.