Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use sys module and os module in python

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, I would like to share with you the relevant knowledge points about how to use the sys module and os module in python. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.

1.sys module

List of common functions of the sys module:

Sys.argv: implements passing parameters from outside the program to the program.

Sys.exit ([arg]): the exit in the middle of the program, arg=0 is the normal exit.

Sys.getdefaultencoding (): gets the current code of the system, which generally defaults to ascii.

Sys.setdefaultencoding (): set the system default encoding. You will not see this method when you execute dir (sys). If you do not pass in the interpreter, you can first execute reload (sys), then execute setdefaultencoding ('utf8'), and set the system default encoding to utf8. (see setting system default coding)

Sys.getfilesystemencoding (): the encoding method is used to get the file system. Return 'return under mbcs',mac' utf-8'. under Windows

Sys.path: get a collection of strings that specify the search path for the module. You can put the written module under a given path and find it correctly when you import in the program.

Sys.platform: gets the current system platform.

Sys.stdin,sys.stdout,sys.stderr: the stdin, stdout, and stderr variables contain stream objects that correspond to the standard Imax O stream. If you need better control over output and print doesn't meet your requirements, they are what you need. You can also replace them, where you can redirect output and input to other devices (device), or handle them in a non-standard way

Import sys# gets a value of the application count a = [11 sys.getrefcount (a)) # the default number of recursions supported by python v1 = sys.getrecursionlimit () print (v1) # input and output (two do not wrap) sys.stdout.write ("hello") sys.stdout.write ("ah") import sys# get script path print (sys.argv) import sys# loop output python You can import the module path for i in sys.path: print (I) import sys# add a new module import path sys.path.append ('D:\\') # there is a qqq.py file under the D:\\ path, which can be imported using import qqq

Note: the module passes parameters (let the user execute the script to pass in the path of the file to be deleted, and internally help the user delete the directory. )

Import sysimport shutil# gets the parameter path = sys.argv [1] # to delete the path directory shutil.rmtree (path) when the user executes the script

Execute procedure: add the directory path to be deleted later

Print added:

#\ nnewline #\ t Tab #\ r returns to the starting position of the current line print ('123\ rature end =') # after printing 123, the cursor returns to the starting position, and write the following 456print ('456 last end ='')

Application (percentage increase of progress bar)

Import time# application: run for i in range (1101) in cmd: msg = "% s%%\ r"% I print (msg,end =') time.sleep (1101) 2.os module (data related to the operating system)

The os module provides functional interface functions of most operating systems. When the os module is imported, it adapts to different operating system platforms and operates according to different platforms. When python programming, it often deals with files and directories, so it can not be separated from os module.

Import os# gets the file size (in bytes) file_size= os.stat ('123.gif'). St_sizeprint (file_size) import os# determines whether the path exists, and returns True if it exists Otherwise, return Falseqqq = os.path.exists ('Dlav 11231') print (qqq) import osqqq = '123.gif'# pass a relative path to get the absolute path v1 = os.path.abspath (qqq) print (v1) import osqqq = r é cue:\ PyCharm\ lol\ 123.gif'# can get the directory above the path v = os.path.dirname (qqq) print (v) import osqqq =' E:\ PyCharm\ lol'www =' 123.txt'# path stitching result = os.path.join (qqq Www) result1 = os.path.join (qqq,'456.txt') print (result) print (result1) import os# shows all files under the path (layer 1) qqq = os.listdir (rattlee:\ PyCharm\ lol\ move1') print (qqq) import osqqq = os.walk (raster:\ PyCharm\ lol') for aMagazine c in qqq: # a: the directory really viewed b: the folder in this directory c: the file print in this directory C)-import os# shows all files under the path (all layers) qqq = os.walk (racy E:\ PyCharm\ lol') for an in qqq c in qqq: for i in c: path = os.path.join (Ameni) print (path)

Generate folder:

Import os# creates a folder named "wdc" under the script path os.mkdir ('wdc') import os# creates a nested folder os.makedirs (r'yhf\ wdc\ www') import osfile_path = r'wdc\ yhf\ www.txt'# get the path directory file_folder = os.path.dirname (file_path) # determine whether the path exists if not os.path.exists (file_folder): # if it does not exist Then create the path os.makedirs (file_folder) else: # prompt print ('directory and exist!') if the path exists

Rename:

Import os# folder rename (original name, new name) os.rename ('wdc','qqq')

Add: escape

# preceded by an'r'to avoid escaping qqq = ringing E:\ PyCharm\ lol\ n123.gif'print (qqq) # where a double slash can also be used qqq ='E:\\ PyCharm\\ lol\\ n123.gif'print (qqq)

Add: progress bar read and write files

Import osimport time# gets the file size (in bytes) file_size= os.stat ('123.gif'). St_sizeprint (file_size) # read the file read_size = 0with open ('123.gifboat technique mode =' rb') one by one, as F1, open ('a.png') Mode = 'wb') as f2: while read_size < file_size: chunk = f1.read (2) # 8 bytes per read f2.write (chunk) read_size = read_size + len (chunk) val = int (read_size / file_size * 100) #\ r: the next print overrides the last print print ('% s%\ r'% (val)) End ='') time.sleep are all the contents of the article "how to use the sys module and os module in python" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report