Skip to content

Instantly share code, notes, and snippets.

@patwooky
Last active December 21, 2016 02:26
Show Gist options
  • Save patwooky/1ae292098abff55919ac4498bea3404e to your computer and use it in GitHub Desktop.
Save patwooky/1ae292098abff55919ac4498bea3404e to your computer and use it in GitHub Desktop.
Common file operations from the Python os module
import os
myPath = r'W:\FROM_TVC'
# list all objects in the directory
[os.path.join(myPath, x) for x in os.listdir(myPath)][:5]
'''
# Result: ['W:\\FROM_TVC\\.DS_Store',
'W:\\FROM_TVC\\._.DS_Store',
'W:\\FROM_TVC\\._9430_Dynamo',
'W:\\FROM_TVC\\._xxxx_Dig_SkyPlus',
'W:\\FROM_TVC\\._9451_Duracell'] #
'''
# get directories
[os.path.join(myPath, x) for x in os.listdir(myPath) if os.path.isdir(os.path.join(myPath,x))==True][:5]
'''
# Result: ['W:\\FROM_TVC\\15125_Sunlight_NaughtyOnes',
'W:\\FROM_TVC\\9685_Clear',
'W:\\FROM_TVC\\9764_Clear_Female_Japan',
'W:\\FROM_TVC\\9794_PAMPERS_FIRST_LEVERAGE_PANTS',
'W:\\FROM_TVC\\9817_Media Globe'] #
'''
# get files
[os.path.join(myPath, x) for x in os.listdir(myPath) if os.path.isdir(os.path.join(myPath,x))==False][:5]
'''
# Result: ['W:\\FROM_TVC\\.DS_Store',
'W:\\FROM_TVC\\._.DS_Store',
'W:\\FROM_TVC\\._9430_Dynamo',
'W:\\FROM_TVC\\._xxxx_Dig_SkyPlus',
'W:\\FROM_TVC\\._9451_Duracell'] #
'''
# replacing the \\ with /. Most of the time it may not be needed
'W:\\FROM_TVC\\9685_Clear'.replace('\\', '/')
# Result: 'W:/FROM_TVC/9685_Clear' #
# checks is file or directory exists
os.path.exists('W:\\FROM_TVC\\9685_Clear') # this is a directory on disk
# Result: True #
os.path.exists('W:\\FROM_TVC\\._9430_Dynamo') # this is a file on disk
# Result: True #
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment