Python standard library OS module, pythonos Module
1. Delete and rename an object
import osimport stringdef replace(file, search_for, replace_with): # replace strings in a text file back = os.path.splitext(file)[0] + ".bak" (1) temp = os.path.splitext(file)[0] + ".tmp" try: # remove old temp file, if any os.remove(temp) (2) except os.error: pass fi = open(file) fo = open(temp, "w") (3) for s in fi.readlines(): fo.write(string.replace(s, search_for, replace_with)) (4) fi.close() fo.close() try: # remove old backup file, if any os.remove(back) except os.error: pass # rename original to backup... os.rename(file, back) (5) # ...and temporary to original os.rename(temp, file)## try it out!file = "samples/sample.txt"replace(file, "hello", "tjena")replace(file, "tjena", "hello")
(1) OS. path. splitext (filename) splits the file name and extension and stores them in a single tuple. However, OS. path. split (path) splits the path into the directory name and file name and stores them in the tuples.
(2) OS. remove (file) deletes the file.
(3) w indicates write-only; others, r indicates read-only; r and w indicate read-only text. B Indicates binary, so rb indicates read-only to binary files. wb indicates write-only to binary files. Generally, the suffix of binary files read and written is dat.
(4) string. replace (s, old, new, maxsplit) replaces all the old parts of the s string with new. Maxsplit is an optional parameter used to control the number of replicas. For example:
>>>import string>>>s = 'abc abcc abccc'>>>string.replace(s, 'c', 'd')'abd abdd abddd'>>>string.replace(s, 'c', 'd', 2)'abd abdc abccc'
(5) OS. rename (old, new) replaces the old file name with new.
2. List Files in the directory
The listdir function in the OS module returns a list Of all file names (including directory names) in the given directory.
>>>import os>>>for file in os.listdir("samples"): print filesample.ausample.jpgsample.wav...
OS. listdir ()The directory name in the brackets (you can understand the directory as a folder ). Note that the directory name is passed in as a keyword and is a string. Therefore, the directory name must be enclosed by quotation marks. In addition, if the directory name is not in the current working directory, you must write the absolute path of the Directory, such as D:/xx/samples. Otherwise, python cannot find the directory.
3. Get and change the current working directory
OS. getcwd () can obtain the current working directory, while OS. chdir () is used to change the current working directory. Take my computer as an example:
>>>import os>>>os.getcwd()'C:\\Python27'>>>os.chdir('C:/Users/Wu/desktop')>>>os.getcwd()'C:\\Users\\Wu\\desktop'
(In my personal experience, if I try to associate the function name with its functions and think about its full name, I can quickly remember the usefulness of this function. Take getcwd as an example. Its function is to obtain the current working directory, so cwd should be the abbreviation of current working directory .)
4. Create and delete multi-level Directories
The makedirs and removedirs functions are used to create and delete multi-level directories. For example, create and delete the exercise directory on the desktop:
>>>os.makedirs('C:/Users/Wu/desktop/exercise')>>>os.removedirs('C:/Users/Wu/desktop/exercise')
Notes:
1. removedirs can only be deletedEmpty directory. The deletion method is as follows: if the directory is empty, it is deleted and recursive to the upper-level directory. If it is empty, delete the directory until the directory at the upper level is not empty.
2. makedirs is createdMulti-level directoryWhile mkdir can only be createdSingle directoryIn other words, except the Created directory, all its parent directories must exist. If the directory does not exist, an error will occur.
3. Similarly, the rmdir function can only be deleted compared to removedirs.Single Empty directoryBut it does not recursively go to the parent directory, check whether it is empty and delete it.
5. Get File Attributes
The stat function can be used to obtain information about an existing file. OS. stat (file) returns a class tuples (stat_result object, containing 10 elements), which are st_mode (permission mode), st_ino (inode number), st_dev (device ), st_nlink (number of hard links), st_uid (owner user ID), st_gid (owner group ID), st_size (file size, bytes), st_atime (last access time ), st_mtime (last modification time), st_ctime (the last metadata/metadata modification time in Unix, and the Creation Time in Windows ). Note the following two points:
1. (st_inode, st_dev) provides a unique identifier for each file in Unix, but it is meaningless on other platforms.
2. st_atime, st_mtime, and st_ctime return a string of numbers, which can be converted to time by using the ctime function in the time module.
For example:
>>>import os>>>import time>>>for i in os.stat('C:/Users/Wu/desktop/exercise/hello.py'): print i332060000022139925900813992590081399259008>>>time.ctime(1399259008)'Mon May 05 11:03:28 2014'