python--File and file systems

Source: Internet
Author: User

One, the file object and the open () function

Introduction of three parameters

binary and text files

Buffer

Sequential and unordered access to files

Properties and methods of the file object

A file object can be iterated

File-like Object

Third, file system operation

Iv. operation of FD

One, the file object and the open () function

The file object is a python built-in data type that can be opened with the open () function to obtain a Document object.

1. Open () function

The format of the open () function is as follows:

Open (filename, mode= ' R ', Bufsize=-1)

Open () Returns a file object, which is an instance of the file type built into Python.

The parameters of the open () function have the following meanings:

    • FileName: Format: string. Meaning: The path to the file to be opened can be either an absolute path or a relative path. Note that on UNIX and Windows, you can use the slash "/" as the delimiter for the directory . In Windows, the path delimiter is the backslash "\", which is the same as the escape symbol in the regular expression, so the Windows file path needs to use "\ \" for the directory , such as: ' C:\\test\\test.txt ', or use raw string in Python, such as R ' C:\test\test.txt ', to represent the path, which is not required in Linux.
    • Mode: Format: String. Meaning: Open the file in either read-write mode. The options for mode can be found below.
    • BufSize: Format: integral type. Meaning: The cache set for the file. Bufsize=0, equivalent to the Unbuffer form, writes to the contents of the file is immediately brushed to the hard disk, bufsize=1, the row buffer, after each write "\ n", the content is brushed to the hard disk. BufSize < 0 o'clock, use the system default buffer size, BufSize > 1 o'clock, use it as the buffer size of the file.

2. Value and meaning of the parameter mode

' R '--read-only mode, which requires the destination file to exist.

' W '--write only mode, if the target file already exists, will truncate the target file and overwrite its contents , if the target file does not exist, create a new one.

' A '--append mode, write-only to open the target file, if the target file already exists, the content is appended to the end of the source file, if the target file does not exist, it is created.

' r+ '--read-write mode, which requires that the target file must exist, writes at this time, does not truncate the source file, but instead replaces the contents of the corresponding location in the source file.

' w+ '--read-write mode, which truncates the target file and overwrites its contents if the target file already exists, and creates a new if the destination file does not exist.

' A + '--append mode, read and write open the target file, if the target file already exists, write the content to append to the end of the source file, if the target file does not exist, it is created.

binary files and text files

The above 6 file open mode, can also be combined with ' B ', ' t ' to form a similar ' RB ', ' wt ' such forms, ' B ' stands for binary mode, ' t ' stands for text mode. by default, Python opens the destination file in text mode.

    • UNIX platform, there is no difference between the two,
    • On the Windows platform, if you open a file in text mode, when you read os.linesep (actually ' \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \)

3. Sequential and non-sequential access to files

Files are sequential in nature, and want to read the contents of the following, it is generally necessary to read the previous content, while the subsequent bytes will not be read before the preceding bytes. However, the file also supports a non-sequential read and write mode, the files object records a current position of its own, and the next read and write will start from this location. The F.tell () function allows you to view the current position and, through the F.seek () function, you can set the current location of the file.

Properties and methods of the file object

F.closed

Read-only property to determine if F.close () has been called.

F.encoding

Read-only properties, file encoding format

F.mode

Read-only property that displays the mode specified when the open file is called

F.name

Read-only property that displays the specified name when the open () file is called

F.newlines

F.softspace

A read-only Boolean property that is used by the print statement to record its own state, and the file object itself does not modify or use the property.

F.errors

F.close ()

Closes the file object that is already open, all of the file objects, after the read and write operations are completed, should be closed

F.flush ()

Manually write python to the file's cache to the operating system

F.isatty ()

Returns true if F is an interactive terminal, otherwise, returns false

F.fileno ()

Returns an integer that is the file description character--file descriptor,fd of the file F.

F.read (size =-1)

Reads the contents of the file and returns it as a string.

Size < 0--always read to the end of the file;

Size > 0--reads the contents of the size byte until the end of the file, and returns the full text if the size byte is still not full at the end of the file.

size = 0--size = 0 or read when the current file's position is at the end of the text, an empty string is returned.

F.readline (size =-1)

Reads 1 rows until it encounters ' \ n ' or reads a size byte, which is returned as a string.

Size >= 0, the read content does not exceed the size byte, if the size byte is not read enough to the end of the bank, then stop reading, return to the bank.

Size < 0, reads the entire contents of the current line until ' \ n ' or the end of the file is encountered.

F.readlines (size =-1)

Reads multiple rows, returns a list, each row as a string in the list. The last string may not end with "\ n".

F.next ()

The file object is iterative, and each iteration returns a row in the document.

F.seek (pos, how = 0)

Sets the position of the current file to the location of the POS byte from the reference point, and how the parameter determines the location of the reference point:

how = 0, the reference point is the beginning of the file, which is the default case, corresponding to the OS. Seek_set

how = 1, the reference point is the current position, which corresponds to the OS. Seek_cur

how = 2, the reference point is the end of the text, corresponding to the OS. Seek_end

F.tell ()

Returns the number of bytes in the file's current location from the beginning of the file.

F.truncate ([size])

Truncates the file to no more than size bytes,

If size exceeds the current file size, it will be populated with 0

If the size parameter is not provided, F.tell () is used as the size of the new file after truncation.

F.write (s)

Writes the string s to a file

F.writelines (LST)

The parameter lst is an iterative object that writes all of its string contents to F, and the function does not automatically add ' \ n '!

A file object that can be iterated

As mentioned earlier, the file object is iterative,

For line in F:    ...

Each row in F is traversed at a time.

File-like Objects and Polymorphic

The concept of File-like objects exists in Python, meaning that objects with partial attributes and functions of the file object, which methods the File-like object needs to implement depend on the client-code that call them, such as they are read-only, You can only implement read operations on file objects, such as the Read () function, File-like is an object that implements only a subset of the function of the file object.

Third, file system operation

The functionality of the OS module consists primarily of the file System section and the process section, which describes the file system-related sections.

When the request operating system fails, the OS module returns the built-in exception exceptions. OSError instance, you can access this type through Os.error, oserror instance has three kinds of attributes:

    • errno: Error code for operating system error
    • Strerror: A string describing the error;
    • FileName: The file on which the operation was faulted.

Useful properties provided by the OS module

>>> Os.curdir
‘.‘

A string representing the current directory, which is "." On both UNIX and Windows.

>>> os.pardir ' ... '

A string representing the parent directory, both UNIX and Windows are ".."

>>> Os.defpath '.; C:\\bin '

The default search path for the program, which is used if the PATH environment variable is missing.

>>> os.linesep ' \ r \ n '

The end string of the text line, on Unix, ' \ n ', on Windows ' \ r \ n '.

>>> os.linesep ' \ r \ n '

Separators for separating file extensions and filenames are "." On Unix and Windows.

>>> os.pathsep '; '

The delimiter used to separate paths in the path list can refer to the PATH environment variable, which is ":" On the UNIX platform and ";" on the Windows platform.

>>> os.sep ' \ \ '

The path consists of a "/" on the UNIX platform and "\ \" on the Windows platform.

File system-related methods provided by the OS module

Os.access (path, mode) # e.g. >>> os.access ("C:\Windows\System32", OS. R_OK | Os. W_OK) True

The access () function determines whether the real user (group) of the current process (real user/real Group) has permission to perform all of the operations listed in mode on path paths, and the optional values for the parameter mode are:

    • Os. F_OK: Whether the file specified by the path exists;
    • Os. R_OK: Whether the file specified by the path is readable;
    • Os. W_OK: Whether the file specified by the path is writable;
    • Os. X_OK: Whether the file specified by the path is executable;

Os.chdir (PATH)
# e.g.
>>> Os.chdir ("c:/")

equals the CD to path, which will switch the PWD to the path specified by path.

Os.chmod (path, mode)

Set the access permission for path to mode, which can be 0 or more OS. R_ok,os. W_ok,os. X_OK, also a 3-bit 8-binary integer (Unix platform), such as 0777, 0664, etc.

OS.GETCWD () #e .g.>>> os.getcwd () ' c:\\ '

GETCWD () Gets the path to the current working directory.

Os.listdir (PATH)

Listdir (path) Returns a list that includes all the files and directories under path paths, but does not include "." and ".." Directory.

The list returned by Listdir () is unsorted.

Os.mkdirs (Path, mode=0777) os.mkdir (path, mode=0777)

Create a directory where path may involve a multi-level directory, Mkdirs will create all directories that do not already exist along the path, and then set access permissions, while mkdir () creates only the base address at the far right of the route, if there is a directory that has not yet been created, mkdir () Throws an exception OSError.

Both functions throw oserror when the creation fails, and the same exception is thrown when the specified path already exists.

Os.remove (path) os.unlink (path)

These two functions delete the file specified by path.

Os.removedirs (PATH)

Remove all directories that pass through the path (the directory that is required to be empty).

Os.rmdir (PATH)

Deletes the directory specified by path (requires a directory to be empty), throws OSError when the deletion fails, for example, the deleted directory is not empty.

Os.rename (SRC, dest)

Rename the file or directory src to dest.

Os.renames (SRC, dest)

Renamed, but the process of renaming will automatically create an intermediate path in the parameter dest that does not already exist, and will delete the empty directories contained in SRC after renaming.

Os.stat (PATH)

Returns a value of type Stat_result that provides 10 information about the path of the parameter, which can be accessed through the corresponding property, for example:

1 >>> os.path.getsize ('test1.py')20L  3 >>> os.stat ('test1.py'). St_size4 0L

The 10 types of information about files, directories, and their corresponding property names are:

Property name Meaning
St_mode Access control and other mode bits
St_ino The ordinal of the I node
St_dev Device number
St_nlink Number of hard links
St_uid The UID of the owner
St_gid The owner of the GID
St_size Size (units: bytes)
St_atime Last access time (number of seconds since epoch)
St_mtime Last Modified Time
St_ctime Time of last state change

Os.utime (Path, Times=none)

Set the last access and last modified time of the file,

    • If the Times is none, then Utime () uses the current time;
    • If the Times is not none, the time must be a two-tuple-(accessed, modified), which specifies the last access and modification, where both values are the number of seconds since the epoch.

Os.walk (Top, topdown=true, Onerror=none)

First, this function is a generator! Used to traverse the directory specified by the parameter top

    • When the parameter topdown is true (the default), traverse from top to its subdirectory
    • When the parameter Topdown is false, the reverse step is started from the leaf node of the top tree, and the inverse traversal

Parameter onerror:

    • If none, walk () ignores all oserror exceptions encountered during traversal
    • Otherwise, it must be a function, with the exception OSError instance as a unique parameter, once walk () encounters an exception, it is passed to the onerror () function, onerror () can be freely defined.

Walk () Each generated item is a ternary group-(Dirpath, dirnames, filenames), where:

    • Dirpath: The name of the directory that is currently traversed;
    • dirnames: List that contains all the immediate subdirectory names of the current directory (excluding "." and "..") );
    • filenames: A list that contains all the file names in the current directory;

Cases:

Import OS  for  in Os.walk ("d:\\programs"):    if   not D.startswith ('. ' )]    for in  filenames:        print os.path.join (Dirpath, Name

This example will print out all the files in the "D:\\programs" directory, all directories that do not start with ".",

Note that when Topdown is true, when traversing to a level directory, modifying the resulting dirnames list can affect the number and order of subdirectories that will be traversed in the next layer, for example, in this case, the "." Is removed. The beginning of the directory.

python--File and file systems

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.