Description of common functions of the OS module in Python

Source: Internet
Author: User

The OS module in the python standard library contains common operating system functions. If you want yourProgramThis module is especially important if it has nothing to do with the platform. That is, it allows a program to run in Linux and Windows without any changes or any problems.

The following lists some useful parts in the OS module. Most of them are simple and clear.

 

OS. SEP can replace the path separator specified by the operating system. \ In Windows

The OS. Name string indicates the platform you are using. For example, for Windows, it is 'nt ', and for Linux/Unix users, it is 'posix '.

The OS. getcwd () function obtains the current working directory, that is, the directory path of the current Python script.

OS. getenv () gets an environment variable. If none is not returned

OS. putenv (Key, value) sets an environment variable value

OS. listdir (PATH) returns all files and directory names in the specified directory.

The OS. Remove (PATH) function is used to delete an object.

The OS. System (command) function is used to run shell commands.

The OS. linesep string specifies the row Terminator used by the current platform. For example, in windows, '\ r \ n' is used, in Linux,' \ n' is used, and in MAC, '\ R' is used '.

The OS. Path. Split (p) function returns the directory name and file name of a path.

The OS. Path. isfile () and OS. Path. isdir () functions verify whether the given path is a file or a directory.

The OS. Path. Existe () function is used to check whether the GIVEN PATH actually exists.

OS. curdir: returns the current directory ('.')
OS. chdir (dirname): change the working directory to dirname

OS. Path. getsize (name): Get the file size. If the name is a directory, return 0l

OS. Path. abspath (name): Obtain the absolute path.
OS. Path. normpath (PATH): standard path string format

OS. Path. splitext (): separates file names and extensions
OS. Path. Join (path, name): Connection directory and file name or directory
OS. Path. basename (PATH): returns the file name.
OS. Path. dirname (PATH): Return file path

 

First Python Program (Python 3.1.2)

 

Create a file (maketextfile. py)

 "This script reminds the user to enter a (non-existing) file name, and then the user enters each row of the file. Finally, write all text to the file"  #! /User/bin/ENV Python  'Maketextfile. py -- create text file' Import osls = OS. linesep # Get filename Filename = input ( 'Enter a file name :' ) While True: If OS. Path. exists (filename): Print ( "Error: '% s' already exists" % Filename) Else : Break  # Get File Content (text) lines All = [] print ( "\ Nenter lines ('.' By iteself to quit). \ n" ) # Loop until user terminates Input  While True: Entry = input ( '>' ) If Entry = '.' : Break      Else : All. append (entry) # Write lines to file with proper line-ending Fobj = open (filename, 'W' ) Fobj. writelines ([ '% S % s' % (X, ls) For X In All]) fobj. Close () print ( "Done! " )

The program is very simple. The following is a relatively complex sentence:

 
Fobj. writelines (['% S % s'% (X, ls)ForXInAll])

This list is parsed and a line terminator is added to each line to the file.

 

Read a file (readtextfile. py)

  #! /User/bin/ENV python   'readtextfile. PY -- read and display text file'   # Get file name  fname = input ( 'Enter File Name: ') print ()  # attempt to open file for reading  try: fobj = open (fname,  'R' ) handle T ioerror as E: print ( "*** file open error" , e)  else :  # display contents to the screen   for  eachline  in  fobj: print (eachline,  end  =  '') fobj. close () 

Some exception handling is added.

It may be strange that I modified this sentence myself.

 
Print (eachline,End='')

The end = ''parameter is added to print to eliminate the line breaks added by print itself. This means that the output display is the same as that of the original file. Otherwise, multiple line breaks are added to each line.

 

You can also use this method to remove the line break.

Print (eachline. Strip ())

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.