cosmogonies.net Blog of cosmogonies.net

trademarks
27May/120

APyTA_14: Most used modules, Exp Files management.

APyTA_14: Most used modules, Exp Files management.

The os module, for Operating System, is a module that helps you deal with your filesystem.
A sub-module, called os.path, will be dedicated to the path resolving and manipulation.
http://docs.python.org/library/os.html and http://docs.python.org/library/os.path.html

You will see in the os doc a lot of low-level functions, because python handle very well the kernel of the file system.
But we do not need that depth, often so let's have a look first about how dealing with files easily:

FILEPATH_ASSTRING=r"F:\PythonCourses\PYTHON_TEST01.txt" #For this test please enter here a path where you have the right to create files.
myFile = open(FILEPATH_ASSTRING,'w')
print type(myFile)#<type 'file'>  Another python object, called a File Descriptor
myFile.write("line1\n")
myFile.writelines(["line2\n","line3\n"])
myFile.close()
print open(FILEPATH_ASSTRING,'r').readlines() #returned as a list of string (lines)
#['line1\n', 'line2\n', 'line3\n'] (to check use REAL notepad, like notepad++, forget the crappy one in windows)

Manage a file with the open built-in function, giving a path (remember the string format for path).
Your variable will not be the string stream, it is an handle, a file - descriptor. Take that object like a cursor into your text editor.
Notice also the second argument. You can open a file in ONE MODE ONLY. 'w' is for write, and if anything in the path already exists, it will purely vanish into the warp !
So be very careful in which mode you have to deal with your file ('w' is write, 'r' for read, 'a' for append).

I hardly show you a full example here, because it will require involving your filesystem, so let's enumerate the most useful functions:
os.mkdir(path) #Create the directory at path (but the sub-path must exist)
os.makedirs(path)#Create the directory at path, and create all parent folder if the sub-path does not exist !
os.rename(OldNamePath, NewNamePath) #Rename the file (but can not change its path).
os.listdir(path) #Get all direct children of current Folder. Could be files or sub-folders !
os.remove(path) #Delete a file, do not work if path is a directory!
os.rmdir(path) #This remove a directory, but only if it is empty
os.chmod(path,mode) #Change the attribute of the file at path (use to put a file in read-only)
os.chown(path, uid, gid) #Change the owner of the file at path (give it to root for example).

import os,os.path
print os.environ #Will display all you need to know about your current machine (USERNAME,COMPUTERNAME,USERDOMAIN, etc.)
myTempFolder = os.environ['TEMP'] #For me it is : 'C:\\Users\\Username\\AppData\\Local\\Temp'
if not os.path.exists(myTempFolder):
  os.makedirs(myTempFolder)
for currentItem in os.listdir(myTempFolder):
  if os.path.isfile(myTempFolder+"\\"+currentItem): #Warning currentItem is JUST the file name.
    print currentItem

The os.path module is a tool to analyze the string as a path one, and the exists function is really mandatory to safely consider the file or dir.
FILEPATH_ASSTRING=r"F:\PythonCourses\PYTHON_TEST01.txt" #remember the r to express the string as RAW ?
os.path.exists(FILEPATH_ASSTRING) # Result: True #
os.path.basename(FILEPATH_ASSTRING) # Result: PYTHON_TEST01.txt #
os.path.dirname(FILEPATH_ASSTRING) # Result: F:\PythonCourses #Returned value is full path of the directory!
os.path.getsize(FILEPATH_ASSTRING) # Result: 18L #  In Bytes
os.path.isdir(FILEPATH_ASSTRING) # Result: False #
os.path.splitdrive(FILEPATH_ASSTRING) # Result: ('F:', '\\PythonCourses\\PYTHON_TEST01.txt') #
os.path.splitext(FILEPATH_ASSTRING) # Result: ('F:\\PythonCourses\\PYTHON_TEST01', '.txt') #
os.path.splitunc(FILEPATH_ASSTRING) # Result: ('', 'F:\\PythonCourses\\PYTHON_TEST01.txt') #   The first tuple will be the start of a UNC path like \\ServerName\...

If you want to copy a file very easily, use the shutil module which can do that for you:
http://docs.python.org/library/shutil.html

import shutil
shutil.copy(SourcePath, DestinationPath) #Copy the file from source to destination
shutil.copy2(SourcePath, DestinationPath) #Idem, but also copy the stat ! (owner, creation date, etc.) A perfect clone!
shutil.copytree(SourcePath, DestinationPath) #Can duplicate recursively a whole filesystem hierarchy.

At last, but not least, os.walk is a very powerful function to explore recursively your filesystem.
Here is the snippet:

fileList=[]
rootdir = os.environ['TEMP']
for root, subFolders, files in os.walk(rootdir):
  for currentFile in files:
    fileList.append(os.path.join(root,currentFile)) #You can use os.path.join instead of the operator +"/"+
import pprint
pprint.pprint(fileList) #Lots of crap right ?
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

service

No trackbacks yet.

advertise
store
service