PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, September 10, 2022

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

 September 10, 2022     cross-platform, path, python     No comments   

Issue

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)


Answered By - daveruinseverything
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing