Home > Net >  Iterate directory without joining file with dir (os.join)
Iterate directory without joining file with dir (os.join)

Time:08-11

Simple question, just wanted to know if there is a package to stop me from having to type the os.path.join and have the file already contain this info.

import os
top = '~/folder'
for file in os.listdir(top):
    full_file_path = os.path.join(top, file)

To

import package
top = '~/folder'
for file in package.listdir(top):
    full_file_path = file

CodePudding user response:

A potential quick and dirty approach:

If your goal is to then open the files and you don't want to have to join, a trick could be to change your working directory:

import os
os.chdir(os.path.expanduser('~/folder'))

for file in os.listdir('.'):
    # do something with file

note that file will not contain the full path to your file, but since you changed your local dir (equiv do cd), you will be able to access the file with just its name.

cleaner:

Aside from that, you can also look into pathlib which is a module that provides nice path utilities.

For example:

import pathlib
path = pathlib.Path('~/folder')

for file in path.glob('*'):
    # do something with file

CodePudding user response:

You should be able to define an alias on your import:

from os.path import join as pjoin

Or simply import it with from ... import, though join is a bit overloaded as a term, given it's implication for strings.

from os.path import join

CodePudding user response:

you can create an alias in case it is helpful to simplify the usage:

J = os.path.join

## -or- ##

import from os :: path.join as J


J(top, file)
  • Related