1/7/2016 - 6:52 PM

File Handling

File Handling

# Get list of all files current working directory
import os 
for dirpath, dirs, files in os.walk(os.getcwd()):
  # Do stuff
  for f in files:
    os.rename(f, 'hi_%s' % f)
# Get path to file relative to the execution of the script.
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)) as f:
    workflow_json = f.read()

Great_source = 'https://pymotw.com/2/ospath/'
# http://stackoverflow.com/questions/3964681/find-all-files-in-directory-with-extension-txt-in-python
# Using glob
import glob, os
for file in glob.glob("*.txt"):

# Using listdir
import os
for file in os.listdir("/mydir"):
    if file.endswith(".txt"):

# Using os.walk
import os
for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))