Discover python os module tutorial, include the articles, news, trends, analysis and practical advice about python os module tutorial on alibabacloud.com
in the middle of the first root path to the last file name . * Print(Os.path.join ('c:\\','a','b','d:\\','C','D.txt')) $ Panax Notoginseng #getting the path will convert the/or \ \ - Print(Os.path.normcase ('c:/windows\\system32\\') ) the #The get path is automatically parsed. return path + Print(Os.path.normpath ('c://windows\\system32\\. /temp/') ) AA='/users/jieli/test1/\\\a1/\\\\aa.py/. /..' the Print(Os.path.normpath (a)) + Print(Os.path.dirname (Os.path.dirname (Os.path.abspath (__file_
The OS module contains common operating system features, and the following list of commonly used commands is as follows:1. Os.sep: Change the path delimiter in the operating system2. OS.GETCWD (): Gets the current path, which is more commonly used in Python code3. Os.listdir (): Lists all files and folders in the current directory4. Os.remove (): Delete the speci
returns child and parent processes (using UNIX)
The Os.plock (OP) locks the program segment into memory. The value of the OP determines which segments are locked
Os.wait () Waits for the child process to complete and returns a tuple that contains its PID and exit status indication: A 16-bit number whose low byte is the signal number that kills the process, its high byte is the exit state (if the signal number is 0), or if the core file is generated, a low byte high is set.
Os.cpu_co
1. Directory Operations#encoding =utf-8Import Unittest,osFrom time import sleepPrint dir (OS)#获取文件路径' Get current path 'OS.GETCWD ()Os.path.abspath (")#新建目录Os.mkdir (' Test_file ')#新建多级目录# os.mkdir (' test_file\\test_1\\test_2 ')Sleep (4)#重命名目录Os.rename (' Test_file ', ' test-1_file ')f = open ('. \\test-1_file\\test.txt ', ' w+ ')F.close ()#删除目录‘‘‘Only empty directories can be deleted, if files or directories in the directory are thrown Windowserror‘
The OS module provides new/delete/view file properties for directories or files, as well as path operations for files and directories. For example: absolute path, parent directory ...OS.SEP can replace the operating system-specific path delimiter. "\ \" under Windows, "/" under LinuxThe OS.LINESEP string gives the line terminator used by the current platform. For example, Windows uses ' \ r \ n ', Linux use
The OS module provides new/delete/view file properties for directories or files, as well as path operations for files and directories. For example: absolute path, parent directory ...OS.SEP can replace the operating system-specific path delimiter. "\ \" under Windows, "/" under LinuxThe OS.LINESEP string gives the line terminator used by the current platform. For example, Windows uses ' \ r \ n ', Linux use
offset. This offset is generally calculated relative to the beginning of the file and is generally a positive number. However, if the whence parameter is provided, whence can be calculated from scratch for 0, and 1 for the current position as its origin. 2 means that the end of the file is calculated as the origin. Note that if the file is opened in a or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is made.fp.truncate([size]) The f
pathPrintOs.path.relpath (filename,'/users')#get the path relative to/users#Absolute PathPrintos.path.abspath (filename)#Standardized PathsPrintos.path.normpath (filename)#get a common path in multiple pathsF1='/users/superdo/zergling/file.txt'F2='/users/superdo/ac/file.txt'f3='/users/superdo/horse/file.txt'PrintOs.path.commonprefix ([F1, F2, F3])#/users/superdo/File properties
os.path.getatimeAccess time (obtained from Os.stat)
os.path.getmtimeModification time (obtained from Os.s
Python's OS module is a module that is closely integrated with the operating system, which provides many more useful methods.
OS.GETCWD () Gets the current working directory, which is the directory where the Python script runs
Print (OS.GETCWD ())Results:/users/ssspure/pycharmprojects/file/osmodule2. Os.c
,'R') GUID= F.readlines () [1].split (': ') [1]# gets the second line of the file with ': ' Split the latterOutfile.write (GUID)# Write output filef.close ()elifOs.path.isfile (Child):# if it is a file, the extension is directly judged ifOs.path.splitext (Child) [1] = ='. Meta': F= Open (Child,'R') GUID= F.readlines () [1].split (': ') [1] Outfile.write (GUID) f.close () outfile.close ()Method Two: The above method can only traverse the level two directory, if you want to traverse the lev
OS module provides an interface for invoking the operating system1. Get the current path>>> Import OS>>> OS.GETCWD ()//equivalent to Linux command pwd'/root '2. Switch directories>>> Os.chdir ("/usr/local")//equivalent to Linux command CD>>> OS.GETCWD ()'/usr/local '3. Create a directory recursively>>> os.makedirs ("/a/b/c")//makedirs can achieve recursive creati
Python OS moduleImport OSOS.GETCWD () # The path to the working directory where the Python script is locatedOs.chdir (R '/tmp ') # switch directory to TMPOs.makedirs (R '/a/b/c ') # Create a multi-tiered folderOs.removedirs (R '/a/b/c ') #删除多层文件夹Os.mkdir ('/A ') # Create a single folderOs.listdir (' home ') # List all folders and filesOs.rename (' A ', ' B ') # M
4. Process-related processingSystem () inputs the current process into the systems shell commandImport OSif Os.name = = "NT":Command = "dir"ElseCommand = "Ls-l"Os.system (command)EXECVP start a new process to replace the current processImport OSImport Sysprogram = "Python"arguments = ["hello.py"]Print OS.EXECVP (program,) + tuple (arguments))Print "Goodbye"Perform new processes with functions such as spawn () under the Windows platformImport OSImport
), os.path.exists (path), returns True if path exists, or if path does not exist, returns Falseos.path.isabs if path is an absolute path, Returns Trueos.path.isfile (path) If path is an existing file and returns True. Otherwise, return Falseos.path.isdir (path) True if path is a directory that exists. Otherwise return Falseos.path.join (path1[, path2[, ...]) When multiple paths are combined, the parameters before the first absolute path are ignored Os.path.getatime (path) returns the last acce
OS ModuleThe OS module is simply a python system-programmed operating module that can handle files and directories that we manually need to do on a daily basis.You can view the Help documentation for the OS module:import
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.