Python file and path operations

Source: Internet
Author: User
Tags lstat

1:OS. Listdir (PATH) // path is the Directory

The function is equivalent to executing the Dir command in the path directory. The returned result is of the list type.
PrintOS. Listdir ('..')

2:OS. Path.Walk(Path, visit, ARG)

Path: the directory to be traversed
Visit: is a function pointer, and the circle of the function is:
Callback (ARG, Dir, filelist)
Where Arg is transmittedWalkArg, DIR is a directory under path, filelist is a list composed of files and directories under DIR, Arg: transmitted to visit

3:OS. Path. Split (PATH)

PATH is a path,

Output: divides the path into two parts, depending on the instance:
PrintOS. Path. Split ("ABC/de.txt ")
('Abc', 'de.txt ')
OS. Path. Split ("ABC ")
(", 'Abc ')
PrintOS. Path. Split ("de/ABC/de ")
('De/abc', 'de ')

4:OS. Path. splitext (filename)
Divide the file name into file names and extensions
OS. Path. splitext (ABC/abcd.txt)
('Abc/abcd', '.txt ')

5:OS. Path. dirname (PATH)
Put forward the directory name
PrintOS. Path. dirname ("ABC ")
# The output is empty.
PrintOS. Path. dirname ('abc \ def ')
ABC

6:OS. Path. basename (filename)
Get the main file name
PrintOS. Path. basename ('abc ')
ABC
PrintOS.Path.basename('abc.txt ')
ABC
PrintOS. Path. basename ('bcd/abc ')
ABC # This does not include the directory name.
PrintOS. Path. basename ('.')
.

7:OS. Mkdir (path, [mode])
Path indicates the directory name. You can only create a level-1 directory.
For example, if path is ABC/DEF, ABC must exist in the current directory; otherwise, it fails.

8:OS. Makedirs (path [, mode])
You can create multi-level directories.

9:OS. Remove (PATH) to delete an object. It must be an object.
OS. Removedirs (PATH) delete all objects in a directory
OS. Rmdir (PATH) to delete a directory, and it must be empty. OtherwiseOS. Errer

10:OS.Walk(PATH)
Traverses the path and returns an object. Each part of the object is a triple.
('Directory x', [directory list under directory X], files under directory X)

Example:
A =OS.Walk('.')
For I in:
Print I

11: shutil. Copy (SRC, DST)
Copy the SRC content of the file to the DST file ., The destination region must be writable. If DST exists, DST is overwritten.

――――――――――――――――――

11.1 OS. path -- common path name Operation

This module implements some useful functions on the path name.

Warning in windows, multiple of these functions cannot correctly support UNC pathnames. Splitunc () and ismount () can handle them correctly.

Abspath (PATH)
Returns a normalized absolute version of the path name. On most platforms, it is equivalent to normpath (join (OS. getcwd (), PATH )). New features in Version 1.5.2.

Basename (PATH)
Returns the name at the bottom of the path name. This is the second half of the pair returned by Split (PATH. Note that the result of this function is different from that of UNIX basename.Program; For UNIX, The basename function returns 'bar' for '/Foo/BAR/', and the basename () function returns an empty string ('').

Commonprefix (list)
Returns the longest path prefix (which is a character). It is the prefix of all paths in the list. If list is empty, an empty string ('') is returned (''). Note that an invalid path can be returned because it operates with one character at a time.

Dirname (PATH)
Returns the Directory Name of the path name. 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 corrupted symbolic connections. On Some platforms, if the permission is not granted to execute the OS. Stat () function on the requested file, false may be returned even if the path actually exists.

Lexists (PATH)
Returns true if path is associated with an existing path. Returns true for corrupted connections. In some platforms that lack OS. lstat (), it is equivalent to exists (). New features in version 2.4.

Expanduser (PATH)
Returns "~ "Or "~ "User" is used as a parameter to replace the START part of the user's home directory. Start "~ "Replace with the environment variable home (if it is set); otherwise, the current user's home directory is queried in the password directory through the built-in module PWD. Start "~ User "is directly queried in the password directory.

On Windows, only "~ "; It is replaced by the Environment Variable home or by a combination of homedrive and homepath.

If the expansion fails or the path does not start with a Tilde, the returned path does not change.

Expandvars (PATH)
Returns the extended parameters using environment variables. The substring in the format of "$ name" or "$ {name}" is replaced by the value of the environment variable name. The incomplete variable name and reference of non-existent variables are left unchanged.

Getatime (PATH)
Returns the last access time of the path. The returned value is the number of seconds from the New Era (see the time module ). If the file does not exist or cannot be accessed, the OS. error is suspended. New features in Version 1.5.2. Change in Version 2.3: If OS. stat_float_times () returns true, the result is a floating point number.

Getmtime (PATH)
Returns the last modification time of path. The returned value is the number of seconds from the New Era (see the time module ). If the file does not exist or cannot be accessed, the OS. error is suspended. New features in Version 1.5.2. Change in Version 2.3: If OS. stat_float_times () returns true, the result is a floating point number.

Getctime (PATH)
Return the ctime of the system. In some systems (such as UNIX), it is the last change time. In other systems (such as Windows), it is the time when the path was created. The returned value is the number of seconds from the New Era (see the time module ). If the file does not exist or cannot be accessed, the OS. error is suspended. New features in Version 2.3.

Getsize (PATH)
In bytes, the size of the path is returned. If the file does not exist or cannot be accessed, the OS. error is suspended. New features in Version 1.5.2.

Isabs (PATH)
Returns true if path is an absolute path name (starting with a slash ).

Isfile (PATH)
Returns true if path is an existing normal file. This is a symbolic connection, so islink () and isfile () can return true for the same path.

Isdir (PATH)
Returns true if path is an existing Directory. This simulates symbolic links, so islink () and isdir () can return true for the same path.

Islink (PATH)
If path references a directory item, it is a symbolic connection and returns true. If symbolic join is not supported, always return false.

Ismount (PATH)
If path is a mount point, return true: a different file system has been mounted at that point in the file system. This function checks whether the path is the parent path, path /.., it is a different device from path, or is it path /.. and path point to the same I-node on the same device-this should be to detect mount points for all UNIX and POSIX variants.

Join (path1 [, path2 [,...])
Intelligently connects one or more Path Components. If any component is an absolute path, all the previous components are discarded (on Windows, including the previous drive name, if any) and the connection continues. The returned value is a combination of path1 and optional path2. It is correctly inserted between two components using a directory separator (OS. SEP), unless path2 is empty. Note that on Windows, because each drive has a current directory, OS. path. join ("C:", "foo") indicates a path (C: Foo) relative to the current directory on drive C:, rather than c: \ Foo.

Normcase (PATH)
Standardize the case sensitivity of a pathname. On UNIX, an unchanged path is returned. On a case-insensitive file system, the conversion path is a lowercase letter. In Windows, it also converts the forward slash to a backslash.

Normpath (PATH)
Standardize a path name. Fold the redundant (or lengthy) separator and locate it in the outer reference so that A/B, A/./B, and A/Foo/../B are both converted to a/B. It is case-insensitive (normcase ()). In Windows, it is converted into a backslash. If it contains a symbolic connection, It should understand the intention that this may change the path!

Realpath (PATH)
Returns the standard path of the specified file name, 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 (indicated by the device number and number of I-nodes ). If OS. Stat () fails to call each path name, an exception is suspended. Valid: Macintosh, UNIX.

Sameopenfile (FP1, fp2)
True is returned if the file descriptors FP1 and fp2 are related to the same file. Valid: Macintosh, UNIX.

Samestat (STAT1, stat2)
Returns true if the stat tuples STAT1 and stat2 are associated with the same file. This structure may be returned by fstat (), lstat (), OR stat. This function uses samefile () and sameopenfile () to achieve basic comparison. Valid: Macintosh, UNIX.

Split (PATH)
Split the path to a center. In (Head, tail), tail is the final path component. The head is anything that directs it. The tail part will not include diagonal lines all the time; If the path ends with a diagonal line, tail will be empty. If no diagonal lines exist in the path, the head is empty. If path is empty, 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 in tail is split by multiple diagonal lines ).

Splitdrive (PATH)
Split the path from the path name to a drive or tail pair. Drive is a description or empty string for each drive. If the drive instruction is not used on the system, the drive will remain empty. In all cases, drive + tail will be the same as path. New features in version 1.3.

Splitext (PATH)
Split the path name to a pair of (root, ext), resulting in root + ext = path. ext is empty or starts with a sentence and only contains one sentence.

Splitunc (PATH)
Split the path name to a pair (UNC, rest) to make it easy for UNC to be a UNC mount point (such as R' \ host \ mount'). If, and the rest of the rest path (such as R' \ path \ file. EXT '). For a path containing the drive name, UNC will always be a null character. Valid: Windows.

Walk (path, visit, ARG)
For each directory in the directory tree with path as the root (including the path itself, if it is a directory), call the visit function with parameters (ARG, dirname, names. The dirname parameter specifies the accessed directory. The names parameter lists the files in the directory (obtained from OS. listdir (dirname ). The visit function can modify names to change the settings of directories accessed under dirname, for example, to avoid access to a part of the tree. (Objects associated with names must be modified at the appropriate location, assigned by del or slice .)

Note: symbols connected to directories are not processed as a sub-directory, and therefore walk () will not access them. To access the Connected Directories, you must identify them with OS. Path. islink (File) and OS. Path. isdir (File) and call walk ().
Author: Shane
Source: http: // bluescorpio .cnblogs.com
The copyright of this article is shared by the author and the blog. You are welcome to repost this article, but you must keep this statement without the author's consent andArticleThe original text connection is clearly displayed on the page. Otherwise, the legal liability is retained.

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.