With the old Ziko python. Catalogue

Source: Internet
Author: User
Python, when installed, comes with a lot of modules, which we call the standard library, one of which is the use of a relatively high frequency, is the OS. There are many methods and properties in this library, and interested crossing can refer to the official documentation: Https://docs.python.org/2/library/os.html, or in interactive mode, with Dir (OS).

Copy the Code code as follows:


>>> import OS #这个动作很重要, cannot be missing
>>> dir (OS)
[' Ex_cantcreat ', ' ex_config ', ' ex_dataerr ', ' ex_ioerr ', ' ex_nohost ', ' ex_noinput ', ' ex_noperm ', ' ex_nouser ', ' EX_OK ', ' Ex_oserr ', ' ex_osfile ', ' ex_protocol ', ' ex_software ', ' ex_tempfail ', ' ex_unavailable ', ' ex_usage ', ' f_ok ', ' NGROUPS_ ' MAX ', ' o_append ', ' o_async ', ' o_creat ', ' o_direct ', ' o_directory ', ' o_dsync ', ' o_excl ', ' o_largefile ', ' o_ndelay ', ' o_ ' NOATIME ', ' o_noctty ', ' o_nofollow ', ' o_nonblock ', ' o_rdonly ', ' o_rdwr ', ' o_rsync ', ' o_sync ', ' o_trunc ', ' o_wronly ', ' p_ ' NOWAIT ', ' P_nowaito ', ' p_wait ', ' r_ok ', ' seek_cur ', ' seek_end ', ' seek_set ', ' Tmp_max ', ' userdict ', ' wcontinued ', ' Wcoredump ', ' wexitstatus ', ' wifcontinued ', ' wifexited ', ' wifsignaled ', ' wifstopped ', ' Wnohang ', ' wstopsig ', ' WTERMSIG ' , ' wuntraced ', ' w_ok ', ' x_ok ', ' _environ ', ' __all__ ', ' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ', ' _copy_reg ', ' _execvpe ', ' _exists ', ' _exit ', ' _get_exports_list ', ' _make_stat_result ', ' _make_statvfs_result ', ' _ Pickle_stat_result ', ' _pickle_statvfs_result ', ' _spawnvef ', ' ABOrt ', ' access ', ' altsep ', ' chdir ', ' chmod ', ' chown ', ' chroot ', ' close ', ' closerange ', ' confstr ', ' confstr_names ', ' Ctermi ' d ', ' CurDir ', ' defpath ', ' devnull ', ' dup ', ' dup2 ', ' environ ', ' errno ', ' Error ', ' execl ', ' execle ', ' execlp ', ' execlpe ', ' E Xecv ', ' execve ', ' execvp ', ' execvpe ', ' extsep ', ' fchdir ', ' fchmod ', ' fchown ', ' fdatasync ', ' fdopen ', ' fork ', ' forkpty ', ' F Pathconf ', ' fstat ', ' fstatvfs ', ' fsync ', ' ftruncate ', ' getcwd ', ' getcwdu ', ' getegid ', ' getenv ', ' geteuid ', ' getgid ', ' get Groups ', ' getloadavg ', ' getlogin ', ' getpgid ', ' getpgrp ', ' getpid ', ' getppid ', ' getresgid ', ' getresuid ', ' getsid ', ' Getuid ', ' initgroups ', ' isatty ', ' kill ', ' killpg ', ' lchown ', ' linesep ', ' link ', ' listdir ', ' lseek ', ' lstat ', ' major ', ' mak Edev ', ' makedirs ', ' minor ', ' mkdir ', ' mkfifo ', ' Mknod ', ' name ', ' nice ', ' open ', ' openpty ', ' pardir ', ' path ', ' pathconf ', ' Pathconf_names ', ' pathsep ', ' pipe ', ' popen ', ' popen2 ', ' popen3 ', ' popen4 ', ' putenv ', ' read ', ' Readlink ', ' Remove ', ' Remov ' Edirs ', ' Rename ', ' Renames ', ' RmdiR ', ' Sep ', ' setegid ', ' seteuid ', ' setgid ', ' setgroups ', ' setpgid ', ' setpgrp ', ' setregid ', ' setresgid ', ' setresuid ', ' setr ' Euid ', ' setsid ', ' setuid ', ' spawnl ', ' Spawnle ', ' spawnlp ', ' spawnlpe ', ' spawnv ', ' spawnve ', ' spawnvp ', ' spawnvpe ', ' stat ' , ' stat_float_times ', ' stat_result ', ' statvfs ', ' statvfs_result ', ' strerror ', ' symlink ', ' sys ', ' sysconf ', ' sysconf_ Names ', ' system ', ' tcgetpgrp ', ' tcsetpgrp ', ' tempnam ', ' Times ', ' tmpfile ', ' tmpnam ', ' ttyname ', ' umask ', ' uname ', ' unlink ' ', ' unsetenv ', ' urandom ', ' utime ', ' Wait ', ' wait3 ', ' wait4 ', ' waitpid ', ' walk ', ' write ']

In so many things, this talk only focus on Os.path, really so-called "weak water 3,000, only take a scoop", why so favored it? Because it is in line with the previously mentioned file operation, it is able to manipulate the files of various places (for documents, please refer to: Do not red-headed (1), do not red-headed (2))

There are also many properties about Os.path, which can still be viewed with Dir (Os.path):

Copy the Code code as follows:


>>> dir (Os.path)
[' __all__ ', ' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ', ' _joinrealpath ', ' _unicode ', ' _varprog ', ' Abspath ', ' altsep ', ' basename ', ' commonprefix ', ' curdir ', ' defpath ', ' devnull ', ' dirname ', ' exists ', ' expanduser ', ' Expandvars ', ' extsep ', ' genericpath ', ' getatime ', ' getctime ', ' getmtime ', ' getsize ', ' isabs ', ' isdir ', ' isfile ', ' Islink ', ' ismount ', ' join ', ' lexists ', ' normcase ', ' normpath ', ' os ', ' Pardir ', ' pathsep ', ' realpath ', ' relpath ', ' Samefil ' E ', ' sameopenfile ', ' samestat ', ' Sep ', ' Split ', ' splitdrive ', ' splitext ', ' stat ', ' supports_unicode_filenames ', ' sys ', ' Walk ', ' warnings ']

With so many properties, crossing can use Help () to see the information one by one and understand how it is used. Here are a few common use methods, for crossing to alleviate a little reading English obstacles, but if crossing English is good enough, please read the original document directly. Just like this:

Copy the Code code as follows:


>>> Help (Os.path.split)

Split (P)
Split a pathname. Returns tuple "(Head, tail)" where "tail" is
Everything after the final slash. Either part could be empty.

Some typical examples are described below:

In particular, all of the following actions are entered into the following directory.

Copy the Code code as follows:


qw@qw-latitude-e4300:~/documents/itarticles/basicpython/codes$ pwd
/home/qw/documents/itarticles/basicpython/codes #当前目录

qw@qw-latitude-e4300:~/documents/itarticles/basicpython/codes$ python

Python 2.7.6 (default, Nov 13 2013, 19:24:16)
[GCC 4.6.3] on linux2
Type "Help", "copyright", "credits" or "license" for more information.
>>>

Absolute path to File

Copy the Code code as follows:


>>> Import Os.path
>>> Os.path.abspath ("225.py")
'/home/qw/documents/itarticles/basicpython/codes/225.py '

File 225.py is actually present in the above path, and the absolute path of the file is obtained. However, what if you provide a file that is not in this directory?

Copy the Code code as follows:


>>> os.path.isfile ("225.py")
True

>>> os.path.isfile ("2222.py")
False
>>> Os.path.abspath ("2222.py")
'/home/qw/documents/itarticles/basicpython/codes/2222.py '

Os.path.isfile (path), you can determine whether the path is a file, in fact, it is determined in the path, whether the existence of the file, if present, return true, otherwise false. The above operation found that 2222.py this file does not exist in the current directory, however, with Os.path.abspaht ("2222.py") can return an absolute path with the file name of the nonexistent file. It may be understood here that if you want to create this file, it will be placed in that position.

With this understanding, you can also:

Copy the Code code as follows:


>>> Os.path.abspath ("/home/qw/kkkkkkkk.kk")
'/home/qw/kkkkkkkk.kk '

Separate directories and filenames

Copy the Code code as follows:


>>> pn = Os.path.abspath ("225.py")
>>> PN
'/home/qw/documents/itarticles/basicpython/codes/225.py '

>>> Os.path.split (PN)
('/home/qw/documents/itarticles/basicpython/codes ', ' 225.py ')
>>> path, filename = os.path.split (PN) [0], Os.path.split (PN) [1]
>>> Path
'/home/qw/documents/itarticles/basicpython/codes '
>>> filename
' 225.py '

Os.paht.split (), the parameter is the directory plus the file name, you can separate the path and file name. In fact, I see this function is not very smart, you see this

Copy the Code code as follows:


>>> os.path.split ("/home/qw")
('/home ', ' QW ')

>>> os.path.split ("/home/qw/")
('/home/qw ', ')

It is the last group to think of the file name, that is, the last/next is the file name, so the second experiment, the file name is empty. Isn't it a little silly?

Similarly, the files or directories in the parameters are not necessarily real in your computer, see:

Copy the Code code as follows:


>>> os.path.split ("/foo/python/qiwsir/git.git")
('/foo/python/qiwsir ', ' git.git ')

As long as it conforms to the directory writing structure, it can be decomposed.

There are two other properties, which are os.path.split (), where you can get the path and file name separately, which makes the operation easier.

Copy the Code code as follows:


>>> os.path.dirname ("/foo/python/qiwsir/git.git")
'/foo/python/qiwsir '
>>> os.path.basename ("Foo/python/qiwsir/git.git")
' Git.git '

Judge

As mentioned earlier Os.path.isfile () can be used to determine whether a file exists, then determine whether the directory path exists, can you? Can

Copy the Code code as follows:


>>> os.path.exists ("/foo/python/qiwsir")
False
>>> os.path.exists ("/home/qw/documents")
True

The related properties are also determined:

Os.path.isabs (PATH): Determine if path is an absolute path
Os.paht.isdir (PATH): Determine if path is a directory that exists
Combining paths

Combining two or more objects is a common thing, so how do you combine multiple paths together? As follows:

Copy the Code code as follows:


>>> os.path.join ("/home/python", "/basicspython", "226.md")
'/basicspython/226.md '

Specifically, the first absolute path is ignored in the return value of this property.

Copy the Code code as follows:


>>> Os.path.join ("/", "/home/qw", "learnpython.md")
'/home/qw/learnpython.md '
  • 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.