Python module knowledge 6: OS, SYS module, pythonos

Source: Internet
Author: User

Python module knowledge 6: OS, SYS module, pythonos

1. OS modules related to the system, such as obtaining paths, directories, and folders

Common Methods:

  • OS. getcwd () # obtain the current working directory, that is, the directory path of the current Python script.

  • OS. rename ('oldname', 'new') # rename a file/directory

  • OS. path. abspath (path) # returns the absolute path of path normalization, which contains the file name

  • OS. path. dirname (path) # get the name of the folder where the file is located

  • OS. chdir ("dirname") # change the working directory of the current script, which is equivalent to the cd

  • OS. path. join (path1 [, path2 [,...]) # returns the results of combining multiple paths. The parameters before the first absolute path are ignored.

  • OS. curdir # the current directory is returned :('.')

  • OS. pardir # obtain the string name of the parent directory of the current directory ('..')

  • OS. makedirs ('dir1/dir2') # multi-layer recursive directory can be produced.

  • OS. removedirs ('dirname1') # If the directory is empty, delete it and recursively go to the upper-level directory. If the directory is empty, delete it, and so on.

  • OS. mkdir ('dirname') # generate a single-level Directory, which is equivalent to mkdir dirname in shell.

  • OS. rmdir ('dirname') # delete a single-stage empty directory. If the directory is not empty, it cannot be deleted. An error is returned, which is equivalent to rmdir dirname in shell.

  • OS. listdir ('dirname') # list all files and subdirectories in a specified directory, including hidden files, and print them in a list.

  • OS. remove () # delete an object,

  • OS. stat ('path/filename') # obtain file/directory information

  • OS. sep: The Path delimiter specified by the operating system. In Windows, it is \, and in linux, It is "/"

  • OS. linesep # pay in the row used by the current platform, "\ t \ n" in win, and "/n" in Linux"

  • OS. pathsep # string used to separate file paths

  • OS. name # the string is only the current platform, win-> 'nt '; Linux-> 'posix'

  • OS. system ("bash command") # Run the shell command to directly display

  • OS. environ # obtain system environment variables

  • OS. path. split (path) # splits the path into two groups of directories and file names.

  • OS. path. basename (path) # returns the last file name of the path. If path ends with a slash (/) or slash (\), a null value is returned, that is, OS. path. split (path) second element

  • OS. path. exists (path) # True is returned if path exists. False is returned if path does not exist.

  • OS. path. isabs (path) # If path is an absolute path, True is returned.

  • OS. path. isfile (path) # If path is an existing file, True is returned; otherwise, False is returned.

  • OS. path. isdir (path) # If path is an existing Directory, True is returned; otherwise, False is returned.

  • OS. path. getatime (path) # Return the last access time of the file or directory pointed to by path


Usage case:

Case 1: Obtain the absolute path and folder respectively

Import OS
Print (OS. getcwd () # C: \ Users \ huhuanhuan \ PycharmProjects \ study2017
Print (OS. path. abspath (_ file _) # obtain the absolute file path C: \ Users \ Huanhuan \ PycharmProjects \ study2017 \ s1.py
Print (OS. path. abspath ("s2.py") # obtain the absolute file path C: \ Users \ Huanhuan \ PycharmProjects \ study2017 \ s2.py
Print (OS. path. dirname (OS. path. abspath (_ file _) # obtain the file's folder C: \ Users \ Huanhuan \ PycharmProjects \ study2017
Print (OS. path. dirname (OS. path. dirname (OS. path. abspath (_ file _) # C: \ Users \ Huanhuan \ PycharmProjects

Effect:

Case 2: Obtain the absolute path and parent folder

import os
base_dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(os.path.abspath(__file__))
print(os.path.dirname(os.path.abspath(__file__)))
print (base_dir)

Effect:

Case 3: The program is often used in combination with sys to automatically add Directories

Case 4: OS. rename ('oldname', 'new') # rename a file/directory

If it is in the same directory as the program, you can directly write the file name. If it is not in the same directory, You need to specify a detailed path.


Case 5: OS. chdir ("dirname") changes the working directory of the current script, which is equivalent to the cd


2. SYS module

The sys module is the interface that the python program uses to request the interpreter's behavior. For example, for debugging classes (trace, frames, writable T), profiling classes (stats, getsizeof), runtime environment classes (python path, stderr, stdout ), interpreter itself (such as version ). Inspect can be regarded as a packaging of sys functions to some extent.


Case 1: command line parameter List. The first element is the program path. sys. argv [0] is the script name.

Import sys

Print (sys. argv)

Result:

['C:/Users/.../PycharmProjects/study2017/s2.py ']


Case 2: return the version information of the python Interpreter

Print (sys. version)

3.5.1 (v3.5.1: 37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)]


Case 3: The module finds the directory priority.

Sys. path is the path set of the python search module and is a list

import sys
for item in sys.path:
print(item)

Search priority:

Case 4: If s2 is not in the system directory, you can add it first and then import the s2 file:

Import sys
Sys. path. append ('d: \ ') # import the D folder
Import s2 # file name

Use sys. path. append (path) to add the relevant path. However, after exiting the python environment, the path you added automatically disappears!


If you need to better control the output, and print cannot meet your requirements, you can use the standard write function; sys. stdout. write (), sys. stdout. flush ().

Case 5: progress bar case: it will show that 1% is always changed to 100%

Import time
Import sys
Def view_bar (num, total ):
Rate = num/total
Rate_num = int (rate * 100)
# D = '\ r % d %' % (rate_num,) # \ r indicates returning to the first position of the current row. It must be used together with the time, or there will be errors in the hour hand, and it will be displayed as a constant number, such as 17%
D = '\ r % s> % d %' % ("=" * num, rate_num) # if this statement is used, the display mode can be ==========================> 17%
Sys. stdout. write (d)
Sys. stdout. flush ()

If _ name __= = '_ main __':
For I in range (0,101 ):
Time. sleep (0.5)
View_bar (I, 100)

Effect:

Until 100%


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.