Python file and path operation function Summary

Source: Internet
Author: User
Tags lstat
1:os.listdir (path)//path as Directory
function is equivalent to executing the dir command in the path directory, returning to the list type
Print Os.listdir ('.. ')
2:os.path.walk (Path,visit,arg)
Path: Is the directory that will be traversed
Visit: Is a function pointer, the function circle is:
Callback (Arg,dir,filelist)
Where Arg is passed to walk Arg, dir is a directory under Path, FileList is a list of files and directories under Dir, ARG: passed to visit
3:os.path.split (PATH)
Path is a route,
Output, the path is divided into two parts, in particular, see the example:
Print Os.path.split ("Abc/de.txt")
(' abc ', ' De.txt ')
Os.path.split ("abc")
(", ' abc ')
Print Os.path.split ("De/abc/de")
(' de/abc ', ' de ')
4:os.path.splitext (filename)
Divide the file name into filename and extension
Os.path.splitext (Abc/abcd.txt)
(' Abc/abcd ', '. txt ')
5:os.path.dirname (PATH)
Put the name of the catalogue.
Print Os.path.dirname ("abc")
#output is empty
Print os.path.dirname (' abc\def ')
Abc
6:os.path.basename (filename)
Get the main file name
Print Os.path.basename (' abc ')
Abc
Print os.path.basename (' abc.txt ')
Abc
Print os.path.basename (' bcd/abc ')
ABC #Note that this does not include the directory name
Print Os.path.basename ('. ')
.
7:os.mkdir (path, [mode])
Path is a directory name: there is a requirement to create only one level directory
For example, path is Abc/def, the current directory must exist ABC otherwise failed
8:os.makedirs (path [, mode])
You can create multi-level catalogs
9:os.remove (path) Delete a file, it must be a file
Os.removedirs (path) Delete everything under a directory
Os.rmdir (path) deletes a directory and must be empty, otherwise os.errer
10:os.walk (PATH)
Traverse path, return an object, and each of his parts is a ternary group
(' Directory x ', [Directory x under directory list], directory x Files below)
Example:
A = Os.walk ('. ')
For I in A:
Print I
11:shutil.copy (SRC,DST)
Copy the file src contents to the file DST. , the destination zone must be writable, and DST is overwritten if DST is present
――――――――――――――――――
11.1 Os.path--Common path name operation
This module implements some functions that are useful on the path name.
Warning: Multiple of these functions do not correctly support UNC pathname on Windows. Splitunc () and Ismount () are able to handle them correctly.
Abspath (PATH)
Returns a normalized absolute version of the path pathname. On most platforms, it is equivalent to Normpath (Join (OS.GETCWD (), path)). New features in the 1.5.2 version.
basename (PATH)
Returns the name at the bottom of the path pathname. This is the second half of the pair returned by split (path). Note that the result of this function differs from the UNIX basename program; UNIX's basename Returns ' bar ' for '/foo/bar/', and the basename () function returns an empty string (').
Commonprefix (list)
Returns the longest path prefix (the character that takes the character), which is a prefix for all paths in the list. Returns an empty string (') If the list is empty. Note You can return an invalid path because it operates one character at a time.
DirName (PATH)
Returns the directory name of the path pathname. This is the first half of the pair returned by split (path).
Exists (PATH)
Returns true if path is associated with an existing path. Returns False for a damaged symbolic connection. On some platforms, if the permission is not granted to execute Os.stat () on the requested file, this function may return false even if the path actually exists.
Lexists (PATH)
Returns True if path is associated with an existing path. Returns True for a corrupted connection. On some platforms lacking os.lstat () the equivalent of exists (). New features in version 2.4.
Expanduser (PATH)
On UNIX, return "~" or "~user" as a parameter that replaces the beginning of the user's home directory. The "~" of the start is replaced by the environment variable HOME (if it is set); Otherwise the current user's home directory is queried through the built-in module pwd in the password directory. The starting "~user" is queried directly in the password directory.
On Windows, only "~" is supported; it is replaced by the environment variable HOME or by a combination of homedrive and HomePath.
If the extension fails or if the path does not start with a tilde, the path returned is unchanged.
Expandvars (PATH)
Returns the parameters that are expanded using environment variables. Substrings of the "$name" or "${name}" format are replaced by the value of the environment variable name. Incomplete variable names and references to non-existent variables are abandoned without change.
Getatime (PATH)
Returns the last access time for path. The value returned is a number of seconds from the beginning of the new era (see Time module). Suspend Os.error If the file does not exist or is inaccessible. New features in the 1.5.2 version. Changes in version 2.3: if Os.stat_float_times () returns True, the result is a floating-point number.
Getmtime (PATH)
Returns the time when the path was last modified. The return value is a number of seconds from the beginning of the new era (see Time module). Suspend Os.error If the file does not exist or is inaccessible. New features in the 1.5.2 version. Changes in version 2.3: if Os.stat_float_times () returns True, the result is a floating-point number.
Getctime (PATH)
Returning the system's CTime, on some systems (like Unix) is the last time to change, on some other systems (like Windows), is the time that path was created. The return value is a number of seconds from the beginning of the new era (see Time module). Suspend Os.error If the file does not exist or is inaccessible. New features in version 2.3.
GetSize (PATH)
Returns the size of the path, in bytes. Suspend Os.error If the file does not exist or is inaccessible. New features in the 1.5.2 version.
Isabs (PATH)
Returns true if path is an absolute pathname (starting with a slash).
Isfile (PATH)
Returns true if path is a normal file that already exists. This mimics the symbolic connection, so Islink () and Isfile () can return true for the same path.
Isdir (PATH)
Returns True if path is a directory that already exists. This mimics the symbolic link, so Islink () and Isdir () can return true for the same path.
Islink (PATH)
If path refers to a directory entry, it is a symbolic connection and returns True. False is always returned if symbolic connections are not supported.
Ismount (PATH)
If the pathname path is a mount point returns True: At that point in the file system, a different file system is already mounted. This function detects if path is the parent, path/:, and path is a different device, or is path/. and path point to the same i-node on the same device-this should be a mount point for all Unix and POSIX variants.
Join (path1[, path2[, ...])
Intelligently connects one or more of the path components. If either component is an absolute path, all the preceding components are discarded (on Windows, including the previous drive name, if any), and continue the connection. The returned value is a combination of path1, optionally path2, and so on, correctly inserted into a directory separator (OS.SEP) between two components, unless path2 is empty. Note on Windows, because each drive has a current directory, Os.path.join ("C:", "foo") represents a path relative to the current directory on drive C: (C:foo) instead of C:\\foo.
Normcase (PATH)
Normalizes the case of a pathname. On UNIX, returns the unchanged path; On a case-insensitive file system, it converts the path to lowercase letters. On Windows, it also converts a forward slash to a backslash.
Normpath (PATH)
Standardize a path name. Folds redundant (or lengthy) separators and locates in outer references, so that a//b,a/./b and a/foo/. /b all become A/b. It is not standardized case (standardized case with normcase ()). On Windows, it converts a forward slash to a backslash. If it contains symbolic connections, it should understand that this may change the intent of the path!
Realpath (PATH)
Returns the path of the specified file name standard, excluding any symbolic connections encountered in the path, if supported by the operating system. New features in version 2.2.
Samefile (path1, path2)
Returns True if the path name parameter is associated with the same file or directory (represented by the device number and i-node number). If Os.stat () calls each pathname fails to suspend an exception. Valid: Macintosh,unix.
Sameopenfile (FP1, FP2)
Returns True if the file descriptor FP1 and FP2 are connected to the same file. Valid: Macintosh,unix.
Samestat (STAT1, STAT2)
Returns True if the stat tuple STAT1 and STAT2 are connected to the same file. This structure may be returned by Fstat (), Lstat (), or stat (). This function uses Samefile () and sameopenfile () to achieve a basic comparison. Valid: Macintosh,unix.
Split (PATH)
Split path name path into a pair, (head, tail) tail is the last pathname component head is anything that guides it. The tail section will never include a slash; if path ends with a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. The trailing slash is removed from the head unless it is the root (one or more slashes only). In almost all cases, join (head, tail) is equivalent to path (only one exception is when the head is split from tail by multiple slashes).
Splitdrive (PATH)
Split path name path to a (drive, tail) pair, drives is a description of each driver or an empty string. Drive instructions are not used on the system and will always be null characters. In all cases, drive + tail will be the same as path. New features in version 1.3.
Splitext (PATH)
The path name is split into a pair (root, ext) so that root + ext = = Path, and ext is empty or starts with a period and contains only one period.
Splitunc (PATH)
The partition path name path to a pair (UNC, rest) in order to facilitate UNC is a UNC mount point (such as R ' \\host\mount ') if, and rest of the remainder of the path (such as R ' \path\file.ext '). For a path that contains a drive name, the UNC will always be a null character. Valid: Windows.
Walk (path, visit, ARG)
For each directory in a directory tree rooted in path (containing the path itself, if it is a directory), the function visit is called with parameters (ARG, dirname, names). The parameter dirname specifies the directory to be accessed, and the parameter names lists the files in the directory (from Os.listdir (dirname)). The visit function can modify names to change the settings of the directory accessed under DirName, for example, to avoid accessing a portion of the tree. (Objects connected by names must be modified in the appropriate location and assigned using Del or slice.) )
Note: Symbolic connections to directories are not processed as a subdirectory, and therefore walk () will not access them. Access the connected directory you must identify them with Os.path.islink (file) and Os.path.isdir (file), and you must call walk ().
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.