Pages

Monday, October 22, 2012

Three packages for file utilities in python

os.path

Python provides useful features for checking files and creating files/directories. The small issue is that the packages one need to use the features are not one, but three. For file checking, one can use os.path.exists() method. This can be used for file and directory existence checking.
# Directory check
os.path.exists(DIRECTORY)
# File check 
os.path.exists(FILEPATH)
os.path has more interesting utilities as you can find in this site. The return value of os.path.split is a tuple with 2 elements, and you can get the same result with os.path.dirname and os.path.basename. You should remember python uses basename with is a little bit hard to conjecture. Using os.path.split(), you can extract the directory name and file name.
# Directory
os.path.split(FILE_PATH)[0]
os.path.dirname(FILE_PATH)
# File
os.path.split(FILE_PATH)[1]
os.path.basename(FILE_PATH)
You have another kind of split, which is splitext. It gives you a tuple of root + ext. For example, you'll get ('hello','.txt') from 'hello.txt'.
# Directory
os.path.splitext(FILE_NAME)[0]
os.path.splitext(FILE_NAME)[1]
os.path.abspath() is also useful method that returns absolute path from relative path.
os.path.abspath(RELATIVE_PATH)

os

However for creating directory, one can use os.makedirs() method.
# Directory check
os.makedirs(DIRECTORY)

shutil

Finally, one can use shell utils (shutil) for copying files. You have two choices: copyfile() for specifying source file to dest file, and copy() method for source file to dest file or directory. You can refer to this site for shutil.
shutil.copyfile(FROM_FILE, TO_FILE)
shutil.copy(FROM_FILE, TO_FILE)
shutil.copy(FROM_FILE, TO_DIRECTORY)

No comments:

Post a Comment