Python OS module (for file or directory operations)

Source: Internet
Author: User
Tags python script

OS Module

OS, semantics for the operating system, contains universal operating system functionality, regardless of the specific platform. When Python is programmed, it handles files and directories such as: Show All files in the current directory/delete a file/get file Size ...

OS module is not limited by the platform, that is to say: when we want to display the current command in Linux to use the PWD command, and windows in the CMD command line to use this, for example: this time we use the Python OS module Os.path.abspath (name) function, no one is Linux or Windows can get the current absolute path.

List of common functions
  • os.name : Indicates the work platform you are using. For example, for Windows, the return is ' NT ', and for Linux/unix users, the return is ' POSIX '.

  • os.sep : Supersedes the operating system-specific path delimiter

  • os.getcwd : Gets the current working directory, which is the directory path of the current Python script work.

  • os.getenv()and os.putenv  : To read and set environment variables, respectively

  • os.listdir() : Returns all file and directory names under the specified directory

  • os.remove(file) : Delete a file

  • os.stat(file) : Get File properties

  • os.chmod(file) : Modify file permissions and timestamps

  • os.mkdir(name) :Create a Directory

  • os.rmdir(name) : Deleting a directory

  • os.removedirs(r“c:\python”): Delete Multiple directories

  • os.system(): Run shell command

  • os.exit(): Terminates the current process

  • os.linesep: Gives the line terminator for the current platform. For example, Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R '

  • os.path.split(): Returns the directory name and file name of a path

  • os.path.isfile()and os.path.isdir() separate check whether the given path is a directory or a file

  • os.path.existe(): Verify that the given path does exist

  • os.listdir(dirname): Lists the directories and files under DirName

  • os.getcwd(): Get the current working directory

  • os.curdir: Returns the current directory ('. ') )

  • os.chdir(dirname): Change working directory to DirName

  • os.path.isdir(name): Determines whether the name is a directory, not the directory returns false

  • os.path.isfile(name): Determine if the name of this file exists, does not exist return false

  • os.path.exists(name): Determine if there is a file or directory name

  • os.path.getsize(name): Or get file size, if name is directory return 0L

  • os.path.abspath(name): Get Absolute path

  • os.path.isabs(): Determines whether an absolute path

  • os.path.normpath(path): Canonical Path string form

  • os.path.split(name): Split file name and directory (in fact, if you use the directory completely, it will also separate the last directory as the file name, and it will not determine whether the file or directory exists)

  • os.path.splitext(): Detach file name and extension

  • os.path.join(path,name): Connection directory with file name or directory

  • os.path.basename(path): Returns the file name

  • os.path.dirname(path): Return file path

Cases:file Operations

os.mknod("abc.test")        #Create an empty file
openfile = open("abc.test",w)  #直接打开一个文件, create a file if the file does not exist

about the openthe Mode

W Write mode
A append mode opens (starting with EOF, creating a new file if necessary)
R+ Open in read-write mode
w+ Open in read-write mode
A + opens in read-write mode
RB opens in binary read mode
WB opens in binary write mode (see W)
AB opens in binary append mode (see a)
Rb+ opens in binary read/write mode (see r+)
Wb+ opens in binary read/write mode (see w+)
Ab+ opens in binary read/write mode (see A +)

About the functions of the file
Openfile.read ([size])

Size is the length of the read, in bytes

Openfile.readline ([size])

Read a line, if a size is defined, it is possible to return only part of a row

Openfile.readlines ([size])

Take each line of the file as a member of a list and return to the list. In fact, its internal is through the Loop call ReadLine () to achieve. If you provide a size parameter, size is the total length of the read content, which means that it may be read only to a portion of the file.

Openfile.write (str)

Writes STR to a file, write () does not add a newline character after Str

Openfile.writelines (seq)

Write the contents of the SEQ to the file (multi-line write-once). This function simply writes faithfully and does not add anything behind each line.

Openfile.close ()

Close the file. Python will automatically close files after a file is not used, but this feature is not guaranteed and it is best to develop a habit of shutting them down. If a file is closed and then manipulated, it generates VALUEERROR

Openfile.flush ()

Write the contents of the buffer to the hard disk

Openfile.fileno ()

Returns a "file label" for a long integer type

Openfile.isatty ()

Whether the file is a terminal device file (Unix system)

Openfile.tell ()

Returns the current position of the file action tag, starting with the origin of the file

Openfile.next ()

Returns the next line and shifts the file action marker to the next line. When a file is used for a statement such as for ... in file, it is called the next () function to implement the traversal.

Openfile.seek (Offset[,whence])

Moves the file-action marker to the location of 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.

Openfile.truncate ([size])

The file is cut to the specified size, the default is the location of the current file operation tag. If the size of the file is larger, depending on the system may not change the file, it may be 0 files to the corresponding size, it may be some random content to add.

Directory Operations
Os.mkdir ("file") to create a directory named file


To copy a file:

Shutil.copyfile ("Oldfile", "NewFile")

Oldfile and NewFile can only be files.

Shutil.copy ("Oldfile", "NewFile")

Oldfile can only be a folder, NewFile may be a file, or it can be a destination directory

Shutil.copytree ("Olddir", "Newdir")

Copy the folder. Olddir and Newdir can only be directories, and newdir must not exist

Os.rename ("Oldname", "NewName")

Renames a file (directory). The file or directory is using this command

Shutil.move ("Oldpos", "Newpos")

Moving Files (directories)

Os.rmdir ("dir")

Only empty directories can be deleted

Shutil.rmtree ("dir")

Empty directories, contents of the directory can be deleted

Os.chdir ("path")

converting directories, changing paths

Code Demo
#!/usr/bin/env pythonimport osprint os.getcwd () print os.listdir ('/opt ') print Os.mkdir                          (' hehe ') print os.mkdir (' Xixi ') print os.rmdir (' hehe ') Os.mknod ("Abc.test") Print os.rename (' abc.test ', ' zxcv.test ') print os.path.exists (' abc.test ')

Run effect slightly ...


This article is from the "Ink" blog, please be sure to keep this source http://jinyudong.blog.51cto.com/10990408/1916470

Python OS module (for file or directory operations)

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.