Search code examples
pythonpathcross-platform

How to make a Python Glob module work Cross-Platform (os.path issues)?


so I have some files layed out like this: './Example 3/ex3A.txt'

This script basically needs to list the content of a random text file that match the criteria I pass to it (in this case, a number). The actual script does much more things to it, but this is the section I'm having trouble with.

This works perfectly on my linux machine, but I can't figure out how to do this on my coworker's windows pc. I've tried various iterations of os.join.path and the like, but I can't seem to get this to work cross platform.

Here is the stock version of the script that works perfectly on linux:

import os
import sys
import glob
import random

script, dirnum = sys.argv

#Create list of filenames
filenames = glob.glob('./*%s/*%s*.txt' % (dirnum, dirnum))

#Open Random file from list
select_file = open(random.choice(filenames))
file_content = selct_file.read()
print(file_content)

Solution

  • You should be able to use os.path.join to create a platform agnostic file path to use with glob:

    search_path = os.path.join('*%s*' % dirnum, '*%s*.txt' % dirnum)
    filenames = glob.glob(search_path)