简体   繁体   English

如何使 Python Glob 模块跨平台工作(os.path 问题)?

[英]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'所以我有一些这样的文件:'./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.这在我的 linux 机器上完美运行,但我不知道如何在我同事的 windows 电脑上执行此操作。 I've tried various iterations of os.join.path and the like, but I can't seem to get this to work cross platform.我已经尝试了 os.join.path 等的各种迭代,但我似乎无法让它跨平台工作。

Here is the stock version of the script that works perfectly on linux:这是在 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 : 您应该能够使用os.path.join创建与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:扩展@daveruinseverything 的回复,您可以选择使用pathlib.Path和 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 /**/ .这同样适用于使用/**/的递归搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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