Python file operations, OS modules, object-oriented

Source: Internet
Author: User
Tags symlink

One file operation 1 file system and files

The ability to read and write files on disk is provided by the operating system, and the modern operating system does not allow the normal program to manipulate the disk directly, so the read-write file is requested by the operating system to open a file object (often referred to as a file descriptor) and then read the data from the file object (read file) through the interface provided by the operating or write the data to this file object (write file).
A file is a named storage area of the computer that is managed by the OS, and in Linux, the file is considered a sequence of bytes

2 python built-in open file mode opens read 1 file opens open

Open (file directory (can be absolute and relative) [File open mode] [file output CACHE])
The following two items are optional parameters. The default return is the memory of a file object, and its default read-write mode is read-only.

can be output by assignment read (bytes of output) default is all


Specify the range of reads by parameter:

2 Mode of file operation

3 other properties of the file 1 common operations for files

A Seek ([file offset] [file pointer position])
Return of the file pointer
0 indicates the start of the file, 1 represents the current position, and 2 indicates the end position.
The first line of the file can be read repeatedly by specifying a pointer to the file.

The size of the offset is expressed as the number of bytes of the file, when it is positive, it is read to the right, and when it is negative, it is read to the left, and when it is 0 o'clock, it is not offset

B tell () shows where the pointer is currently located

C Close () indicates closing the current file

D closed Check whether the current file is closed or true to indicate that it is closed, or false if it is not closed

E Name view file name

F mode to view the open mode of the current file

G Flush Flushes the contents of the current file to disk, which is intended to prevent a power outage and save.

H Next () is used to read the contents of a file, each time it reads a row, its pointer position does not change

2 reading of the file

A ReadLine () reads the contents of A row of files each time

B readlines () reads all the contents of the file every time

C Read () Specifies the number of bytes to read from the file, and the default is to read all

3 Writing of files

A write () which can write to a string,

B Writelins () for passing in multiple parameters

Two OS modules

Role: A module used to make Python more tightly connected to a file system

1 Common OS module methods 1 directory-related directory related

Os. Chdir () Change directory/change working directory by file description
Os.chroot () sets the root directory of the current process
Os.listdir () lists all filenames under the specified directory
Os. Mkdir () Create the specified directory, default to level
Os.makedirs (' x/y/z ')
OS.GETCWD () Gets the current directory
Os. Rmdir () Delete directory
Os. Removedirs () Deleting a multilevel directory
Os.removedirs ('/MNT/AAA/BBB/CCC ') must have all the directories to be deleted

2 File related

Os.mkfifo () Create a FIFO pipeline (named
Os.mknod (): Create a Device file
Os. Remove () Delete file
Os. Unlink () Delete link
Os. Rename () file Rename
Os.rename (' passwd ', ' AAA ')
Os. Stat () returns file status information
Os. Symlink () Create file links, Symbolic links
in [[]: Os.symlink (' text2.txt ', ' Text2.syslink ')
Text2.syslink
Os.utime () Update the file's event stamp UpdateTime
Os.tmpfile () Create and open a new temporary file, open mode Yes (W+B)

3 access Rights related

Os.access () Verify permission mode
In [All]: os.access ('/tmp/text2.txt ', 0) UID Administrator's access rights
Os. OUT[42]: True
In []: os.access ('/tmp/text2.txt ', 100) access rights for ordinary users
OUT[43]: False
Os. Chmod () Modify Permissions
In []: Os.chmod (' Text2.txt ', 0640) os.chmod (' AAA ', 0777) for four-bit
Os. Chwon modification of owner, genus Group
in [+]: Os.chown (' Text2.txt ', 1000,1000)
[[email protected] tmp]# ID admin
uid=1000 (Admin) gid=1000 (admin) group =1000 (Admin)
[email protected] tmp]# ll Text2.txt
-rw-r-----. 1 Admin admin 2525 November 20:35 text2.txt
Os. Umask () Set default permission mode

4 File Descriptor Related

Os. Open (): Opens a file, the underlying operating system's open
Os. Read operation of Read () lower IO
Os. Write () Lower IO writes

5 Device file related

Os. Mkdev () Creates a file based on the specified main device number, secondary device number

In [to]: Help (Os.makedev)
Help on built-in function Makedev in module POSIX:

Makedev (...)
Makedev (major, minor), device number
Composes a raw device number from the major and minor device numbers.
(END)
Os. Major () Gets the main device number from the specified device
Os. Minor () Gets the secondary device number from the specified device

2 Os.path Module 1 file path correlation

In []: Import Os.path
A.os.path.basename (): Path base Name
in [+]: file1=os.path.basename ('/ETC/SYSCONFIG/NETW ')
/etc/sysconfig/network/etc/sysconfig/network-scripts/

B.os.path.irname () path directory name

C.os.path.join () consolidates the path base name and directory name into a single name
In []: Os.path.join (DIR1,FILE1)
OUT[60]: '/etc/sysconfig/network-scripts/'
in [+]: for filename in Os.listdir ('/tmp '):
....: Print Os.path.join ('/tmp ', filename)

C. os.path.splist () split file name and file, return dir and basename () tuple
in [+]: os.path.split ('/etc/sysconfig/')
OUT[64]: ('/etc/sysconfig ', ')

D Os.path.Splitext () return (filename,extension) tuple
6]: Os.path.splitext ('/tmp/')
OUT[86]: ('/tmp/', ')

2 File information:

A Os.path.getatime () returns the file's most recent access record
B Os.path.Getctime ()
C Os.path.Getmtime ()
D os.path.Getsize () returns the size of the file

3 Judging the operation of the query class

A os.path.Exists () to determine if the specified file exists and the file does not exist, it is an error to open it in read-only mode.
B Os.path.Isabs () determines whether the specified path is an absolute path
C Os.path.isdir () determines whether the specified path is a directory
D Os.path.Isfiel () determines whether the specified file is a file
E Os.path.Islink () No symbolic link at the time of judgment
F Os.patj.Ismount () is a mount point
G Os.path.Sanefiek () Two paths whether the same file was executed

Three-object-oriented Programming 1 programming Classifications:

1 Process-oriented programming
Command-centric: writing around "What's going On"
Process oriented: program = algorithm + data structure
Process-Oriented Programming: The program has a series of linear steps, the main idea is that the code is used for data, the instruction is the core, the core is the design algorithm,
2 Function-oriented programming
3 Object-Oriented programming
Object-oriented programming--object oriented programming, called OOP, takes objects as the basic unit of a program, an object that contains functions for data and manipulating data.
Process-oriented continuation of function segmentation is called sub-function, to reduce the complexity of the system.
Object-oriented programming (OOP)
program = instruction + data/algorithm + structure
Data-centric: Writing around "Who's going to be affected"
Object-oriented Programming (OOP): organizes programs around data and interfaces that are strictly defined for data, uses data to control access to code, data-oriented, and the actions that can be taken on that data, code execution is over, and data cannot be skipped
Core concepts of object-oriented programming:
The ultimate goal of all programming languages is to provide an abstract approach
Between the machine model ("solution space" or "solution space") and the Problem model ("problem space") that actually solves the problem, the programmer must establish a connection
Abstract the elements in the problem space and their identifiers in the solution space into objects and allow problems to be described rather than scenarios to describe the problem
You can think of an instance (an instance of a class) as a new variable that holds the data, but can perform operations on its own data, and the instance can manipulate its own data.

Class 2 and instance 1 classes:

Defines the structure and behavior (data and code) that are shared by multiple objects of the same type
The class is abstract, the instance is concrete, the class is (conceptual, abstract conceptual model), the class itself cannot be manipulated, it must have an instantiated object to operate
The data and code of the class, and the members of the class
There are two core members within a class: Code and data, called Class members
Data: member variable or instance variable
Member methods: Called methods, code that manipulate data, which defines how member variables are used, so that the behavior and interfaces of a class are defined by methods
Class: The expression of the common characteristics of the same specific therein
State and method composition (the operation that transforms these states) class
Status: Data
Method: Operation

2 Examples:

An instance is a concrete representation of a class, and the purpose of the class exists is to instantiate it. The class is abstract and the instance is concrete.

3 definition of the Operation 1 class

CALSS Class name (parent Class):
The contents of the class
Classes that have parentheses behind them are called modern classes, and no parentheses are called classic classes.
The content inside the parentheses is the name of the parent class, in which all the parent classes are object

View of the class:

Data Properties for Class 2


When the class is instantiated, the properties of the class are unchanged

The data properties of the class are mutable, and the data properties of the class itself are unchanged when the data properties of the classes are modified at the instance.

When the data property of a class changes, the data properties of the instance that were already changed are not changed again, and the data properties of the newly created instance change

3-class method = = = function

A function defined in a class teaches a method, in a method of a class, to require that the first parameter must be self, and that it is actually the object itself after the class is instantiated
Definition of a class method

Invocation of a class method

4 Object-oriented three major features 1 package

Encapsulation is actually encapsulating the data in a place, and then invoking the content or data at a later point
How to call encapsulate data
Called directly through an object
Where init represents a constructor, the method is called when the class is instantiated, because it is a required parameter, so it must be the same number as it should be when it is passed, and of course you can instantiate multiple objects


Calling data within a class through self

Instantiation of a class

2 Inheriting 1 parent and child classes

base classes and derived classes
Where the parent class is also called the base class
Subclasses are also called derived classes
Parent class

Subclasses, which do not define the properties and methods of the class, but inherit the properties of the Class1

The instantiation and result of the subclass, its full inheritance and the properties and methods of the parent class:

When a subclass has its own constructor, whichever constructor is in the subclass

2 overriding the constructor of the parent class

1 through the parent class name. Init (self, parent parameter) override constructor

2 through Super (own class name, self). Init (Formal parameters)
Pros: You do not need to explicitly tell the name of the parent class, and if the parent class changes, simply modify the inheritance relationship following the class statement without modifying the parent class name

Instantiation calls

Multiple inheritance
For the new class, the breadth first
For the classic class, the depth first

For modern classes, when a D instance is called, the result is the output of D, which inherits the output of B when the pass placeholder is in D, and when the result in B is pass, it inherits the output from C.

For the classic class, when the D instance is called, the result is the output of D, when the pass placeholder in D is inherited from the output of B, and when the result in B is pass, it inherits the output from a, because B inherits a because it is in depth first.

3 polymorphism:

When the parent class and child classes have the same method, the call takes precedence over the subclasses ' methods:

4 new class and classic class

Python2.x supports classic and new classes
Python3.x only supports the new class
The classic class, which can not write the parent class.

The new class, which if there is no inherited parent class, writes the object directly, must write the parent class, and if there is a parent class, write the parent class directly

Only the new class supports the MRO () method

Special properties for Class 5

1 class. Name of the names class displays

2 class. doc Class help documentation

3 class. Parent class/base class for base class

4 class. Module class, when it is not the class of the imported module, its execution result is main, when the module is imported, its execution result is the module name

Private properties of Class 6

Get the private properties of a class by using self.__x=x at the time the class is constructed.

1 Introduction

The private properties of the default class cannot be accessed:

It can be accessed by wrapping its private properties into a method for use.

This adorner @property: Defines a class method as the name of a private property, which allows the user to access directly, but cannot be arbitrarily modified;

The method of its adorner is used to redefine a range that accepts a hidden property to modify its value.

The @ property name. Seeter: When assigning a value to a property, make a judgment first; This function is called automatically when the property name =value

By using the Deleter method, you can make the Del property name automatically call the function and perform the action below the high function

@property Applications:
Used for paging, where two values are passed in, one value is the first page, the other is the number of pages per page, and the operation of the list can be done through @property.

2 Inheritance of private attributes

By default, a private property cannot be called directly, and it needs to be disguised as a method to invoke.

In a class, a method that begins with a double stroke is called a private method: A private method cannot inherit.

7 Magic Method Format1 by position symbol:

Where format is followed by the first digit position of 0, the second digit position is 1,


It can format results using the folate type

2 Get results by matching dictionary keys

3 Formatting a specific item of a tuple

4 applications in the class:


Extended:

8 class Method extension

Iteration:
Determine if an object can be iterated to see if the class has a iter method

The other way
GetItem (Self,item):
Used to view the vlaues of a key
SetItem (self,key.values) is used to modify the current values for the specified incoming vlaues when importing a key,values
Delitem (Self,key) The process of deleting a value by specifying a key.
Getslice (SELF,I,J) To view the results of a slice, which is the start and end of the slice, respectively
Setslice (self,i,j,squence): Used to modify the value of a slice, the beginning of the incoming slice, the end, and the field to be modified
Delslice (SELF,I,J): Used to delete the result of the patch

Python file operations, OS modules, object-oriented

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.