Description of the OS module function in Python

Source: Internet
Author: User
Tags python script

Description of common functions of OS modules in Python

The OS modules in the Python standard library contain common operating system features. This module is especially important if you want your program to be platform-agnostic. That is, it allows a program to be written without any changes or problems, and can be run under Linux and Windows.

Some of the more useful parts of the OS module are listed below. Most of them are simple and straightforward.

OS.SEP can replace the operating system-specific path delimiter. "\ \" under Windows

The Os.name string indicates the platform you are using. For example, for Windows, it's ' NT ', and for Linux/unix users, it's ' POSIX '.

The OS.GETCWD () function gets the current working directory, which is the directory path of the current Python script work.

Os.getenv () Gets an environment variable if none is returned

Os.putenv (key, value) sets an environment variable value

Os.listdir (path) returns all file and directory names under the specified directory.

The Os.remove (path) function is used to delete a file.

The Os.system (command) function is used to run the shell command.

The OS.LINESEP string gives the line terminator used by the current platform. For example, Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R '.

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 respectively verify that the given path is a file or a directory.

The Os.path.existe () function is used to verify that the given path really exists

Os.curdir: Returns the current directory ('. ')
Os.chdir (dirname): Changing the working directory to DirName

Os.path.getsize (name): Get file size, if name is directory return 0L

Os.path.abspath (name): Get absolute path
Os.path.normpath (PATH): Canonical path string form

Os.path.splitext (): Detach file name and extension
Os.path.join (path,name): Connection directory with file name or directory
Os.path.basename (PATH): Return file name
Os.path.dirname (PATH): Return file path

First Python program (Python 3.1.2)

Create file (maketextfile.py)

"This script reminds the user to enter a file name (which does not already exist) and then the user enters each line of the file. Finally, write all the text to the file "#!/user/bin/env python' maketextfile.py--Create Text file ' Import Osls = Os.linesep#get filenamefilename = input ( ' Enter a file name: ') while True: if os.path.exists (filename): print ( "ERROR: '%s ') already exists "% filename" else: break #get file content (text ) Linesall = []print ( "\nenter lines ('. ' by Iteself to quit). \ n")  #loop until user term Inates inputwhile true:entry = input ( ' > ') if entry =  ": break else:all.append (entry)  #write lines To file with proper line-endingfobj = open (filename,  ' W ') fobj.writelines ([ '%s%s ' % (x, ls) for x in all]) Fobj.close () print ( "done!")    

The program is very simple, relatively complex on the following words

Fobj.writelines ([in all])
This list parses and writes each line of characters with a line terminator to the file.

Read file (readtextfile.py)

#!/user/bin/env python' readtextfile.py--read and display text file '#get file Namefname = input (' Enter file n Ame: ') print ()#attempt to open file for readingtry:    ' R ') except IOError as E:print ("* * * File Open error", E )end=") fobj.close ()       

This adds some exception handling.

It's probably weird in there.

        end=")       

Adding the end= ' parameter to print will eliminate the newline character added by the print itself, so that the output can be kept as if it were the same as the original, or there would be multiple line breaks for each line.

You can also use this method to remove the line break

Print (Eachline.strip ())

Description of the OS module function in Python

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.