简体   繁体   中英

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)

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)

Extending the reply of @daveruinseverything, you can alternatively use the pathlib.Path and the f-strings:

from pathlib import Path
search_path = Path('./')/ f'*{dirnum}' / f'*{dirnum}*.txt'
filenames = glob.glob(str(search_path))

This works equally well for recursive search using /**/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM