1

I am trying to open a file that has a random time date stamp as part of its name. Most of the filename is known eg filename = 2017_01_23_624.txt is my test name. The date and numbers is the part I am trying to replace with something unknown as it will change. My question relates to opening an existing file and not creating a new filename. The filenames are created by a separate program and I must be able to open them. I also want to change them once they are open. I have been trying to construct the filename string as follow but get invalid syntax.

filename = "testfile" + %s + ".txt"
print(filename)
fo = open(filename)
Dindsy
  • 11
  • 1
  • 3
  • Possible duplicate of [python inserting variable string as file name](http://stackoverflow.com/questions/14622314/python-inserting-variable-string-as-file-name) – bzimor Jan 24 '17 at 03:06
  • Not quite. My filename string is more complicated than that one. – Dindsy Jan 24 '17 at 03:24

1 Answers1

1

You can't open a file with a partial filename containing a wildcard for it to match. What you would have to do it look at all the files in your directory and pick the one that matches best.

Simple example:

import os

filename = "filename2017_" # known section
direc = r"directorypath"

matches = [ fname for fname in os.listdir(direc) if fname.startswith(filename) ]
print(matches)

You can however use the glob module (Thanks to bzimor) to pattern match your files. See glob docs for more info.

import glob, os

# ? - represents any single character in the filename
# * - represents any number of characters in the filename
direc = r"directorypath"
pattern = 'filename2017-??-??-*.txt'
matches = glob.glob(os.path.join(direc, pattern))
print(matches)

Similar to first solution is that you still get back a list of filenames to choose from to then open. But with the glob module you can more accurately match your files if you so need. It all depends on how tight you want it to be.

Steven Summers
  • 5,079
  • 2
  • 20
  • 31
  • Or easy way is using `glob` with wildcards for filenames. Add this `glob` module version – bzimor Jan 24 '17 at 03:42
  • Thanks. I thought I might have had to do that but didn't know the directory commands. I almost have it but my output for the filename is as below. it is including square brackets and ' quotes.C:\TEMP\Python>python test.py ['testfile2017_01.txt'] Traceback (most recent call last): File "test.py", line 9, in fo = open(matches) TypeError: invalid file: ['testfile2017_01.txt'] – Dindsy Jan 24 '17 at 03:54
  • @Dindsy `matches` is a list, you will need to choose a filename from it. Also see updated answer. Might find the `glob` module a better choice. – Steven Summers Jan 24 '17 at 03:59
  • thanks all. I have 1 solution working. I will look at glob as well. Cheers – Dindsy Jan 24 '17 at 04:05