Python File Operations Summary

Source: Internet
Author: User
Tags python script

The importance of file manipulation for programming languages is self-evident, and information technology loses its meaning if the data cannot be persisted.

The contents of the file operation include opening the file, manipulating the file, closing the file

One, open the file

The function of opening the file in Python is open (' filename ', mode= ' R ', encode= ' None '), the Open function returns the handle to the file by default, and we can add, delete, change, and check the file according to the handle. Assign the handle to the variable we define, assuming we define the variable as F, then F=open (' filename ', mode= ' R ', encode= ' utf-8 ') or with open (' filename ') as F.

Note the point:

When the 1.python interpreter opens the file, it operates on the hard disk and requires the kernel state to operate the hard drive, so the Python interpreter is the file read interface that invokes the operating system. The Chinese version of Windows uses the GBK encoding table by default, and Linux defaults to using Utf-8, all if the file under Windows, non-GBK encoded, need to declare the encoding type in the open function, so that the operating system uses the appropriate encoding rules to decode read, prevent serial code, garbled phenomenon.

2.open mainly has three modes, read (R), write (W), append (a), where the default is read mode. The details of each model are described below.

Two, close the file

There are two sets of ways to close a file:

1. Using F.close (), F is the variable name assigned to the handle returned by open.

2. After the program is finished, it is automatically closed. The first method is easily caused by the loss of data when writing to a file. The reason is that when the data is written, the data is saved in memory, the file is written to the hard disk when it is closed, and if the file is not closed, the software crashes, causing the data in memory to be lost and not written to the hard disk. As an optimization of the first shutdown method, it is used: with open (' filename ') as F. With creates a block that places the file action under the WITH program block so that the with control block ends and the file is automatically closed.

The syntax is as follows:

With open (' F1.txt ') as F1, open (' F2.txt ') as F2:    ...

  

Third, the basic method of manipulating Files 3.1 file

Method

Function

F.read ([size])

Size is the length of the read, in bytes

F.readline ([size])

If size is defined, it is possible to return only part of a row

F.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 read only part of the file

F.write (str)

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

F.writelines (seq)

Write the contents of the SEQ to the file. This function is simply written faithfully, and will not add anything behind each line.

F.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

F.flush ()

Write the contents of the buffer to the hard disk, and the data in memory will be flushed to the silver disk.

F.fileno ()

Returns a "file label" for a long integer type

F.isatty ()

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

F.tell ()

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

F.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.

F.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

F.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.

3.2 file read, create, append, delete, empty one, create a new file with Python, the content is a 0 to 9 integer, each number in a row
f = open (' F.txt ', ' W ') for I in Range (0,10):    f.write (str (i) + ' \ n ')
F.close ()
Second, the file content is appended, from 0 to 9 of the 10 random integers
Import RANDOMF = open (' F.txt ', ' a ') for I in Range (0,10):    f.write (str (random.randint (0,9))) f.write (' \ n ') F.close ()
Third, the contents of the file appended, from 0 to 9 of the random integer, 10 digit row, a total of 10 rows
Import RANDOMF = open (' F.txt ', ' a ') for I in Range (0,10): For    I in range (0,10):        f.write (str (random.randint (0,9)))    f.write (' \ n ') F.close ()
Iv. directing the standard output to a file
Import syssys.stdout = open (' Stdout.txt ', ' W ')
Five, read and write the file

5.1, File Open

Read and write properties of the file

The file object has its own properties and methods. First look at the properties of file. (+ and B can be combined with other characters into mode, e.g. RB opens in binary read-only mode, mode parameter is optional, if no default is R)

(Note: After the file is opened, it should be closed in time, you can view the F.closed property to verify that the file is closed)

Mode

function

R

Read-only mode (default, file does not exist, exception occurs) the pointer to the file will be placed at the beginning of the file

W

Write-only mode (readable, file does not exist then create, existing delete content, then open file)

A

Append mode (write only, file does not exist then create, append content exists)

r+

Read/write mode (readable, writable, can be appended)

B

Open in binary mode (for example: FTP send upload ISO image file, Linux can be ignored, Windows processing binary file should be labeled)

w+

Write and reread (readable, writable, append) if the file already exists, overwrite it. If the file does not exist, create a new file.

A +

Same as a (readable and writable, file does not exist then create, append content exists). If the file already exists, the file pointer will be placed at the end of the file. The file opens with an append mode. If the file does not exist, create a new file to read and write.

Rb

Open in binary read mode, only read files, if the file does not exist, an exception will occur

Wb

Open in binary write, can only write files, if the file does not exist, create the file

Ab

Binary write file. Read content from the top of the file add content from the bottom of the file does not exist then create

Rt

Open as text read, only read files, if the file does not exist, an exception occurs

Wt

Open as text, read only the file, and if the file does not exist, create the file. If the file exists. Empty first, then open the file

At

Open as text, read-only, and create the file if it does not exist. If the file exists. Empty first, then open the file

rb+

Open in binary read, can read, write the file, if the file does not exist, an exception will occur

wb+

Open in binary write, can read, write the file, if the file does not exist, create the file. If the file exists. Empty first, then open the file

ab+

Chasing and reading binary. Read content from the top of the file add content from the bottom of the file does not exist then create

5.2. Close File

F.close ()

When the file is read and written, the file should be closed

Six, clear the contents of the file
F.truncate ()

Note: Only files opened in writable mode, such as "r+" "rb+" "W" "WB" "wb+" can perform this function

Seven, pointer location and query of the file

7.1, File pointer:
When the file is opened, its object is stored in F, which remembers the current location of the file so that it can perform a read, write operation, which is called a pointer to the file (a long type of bytes that starts at the head of the file).

7.2, the location when the file opens:

with "R" "r+" "rb+" read mode, "W" "w+" "wb+" to open the file,
At first, the file pointer points to the file's head.

7.3, gets the value of the file pointer:

L = F.tell ()

  
7.4, move the pointer to the file

The F.seek (offset, option) option = 0 o'clock indicates that the file pointer is pointing from the head of the file to the "offset" byte.      option = 1 o'clock, which indicates that the file pointer points to the current position of the file and moves the "offset" byte backwards. option = 2 o'clock, which means pointing the file pointer from the end of the file, moving the "offset" byte forward.
Eight, read content from file

8.1, reading of text files (files opened in "RT" mode)

s = F.readline (     )        return value: S is a string that reads a line from a file with a line terminator.        Description: (1)  if Len (s) =0 indicates the end of the file                    (2)   if it is the last line of the file, there may not be a line terminator

8.2, reading of binary files (files opened in "RB", "rb+", "wb+" mode)

s = F.read (    N)     Description: (1)  if Len (s) =0 indicates that a file has been read to the end of the file                  (2)   , the pointer to the file moves back len (s) bytes.                (3) If the track is bad, an exception occurs.
Nine, write a string to the file
F.write (    s)    parameter:       s The string description to write    : (1) After the file is written, the pointer to the file moves the Len (s) byte backwards.                 (2) If the track is bad, or the disk is full, an exception occurs. Return value: S is a string that reads content from a file
X. Delete a file
Import osos.remove (file)

Import OS
Os.remove (' S.txt ')
3.3 Python reads the contents of a file by line in two ways

Method One:

For on open (' F.txt '):    print (line)

Method Two:

F =open (' F.txt ', ' R ') lines =f.readlines () for I in lines:    print (i)
3.4 File Positioning

The tell () method tells you the current position within the file, in other words, the next read and write will occur after so many bytes at the beginning of the file.

The Seek (offset [, from]) method changes the position of the current file. The offset variable represents the number of bytes to move. The from variable specifies the reference position at which to begin moving bytes.

  If from is set to 0, this means that the beginning of the file is used as the reference location for moving bytes.

If set to 1, the current position is used as the reference location.

If it is set to 2, then the end of the file will be used as the reference location.

Example:

#打开一个文件f =open (' f.txt ', ' r+ ') Str_read = F.read ("read string is:%s"% str_read) #查找当前位置position = F.tell () print ("Current position: %s "%position) #把指针再次重新定位到文件开头position =f.seek (0,0) str_read =f.read (" Reread read string:%s "% str_read) # Close file F.close () Result: the string to be read is: 2204513940 the current position: 10 The reread read string is: 2204513940
3.5 Renaming and deleting files

Python's OS module provides a way to help you perform file processing operations, such as renaming and deleting files.

To use this module, you must first import it before you can invoke the various functions associated with it.

Rename () Method:

The rename () method requires two parameters, the current file name, and a new filename.

Grammar:

Os.rename (Current_file_name, New_file_name)

Example:

Import os# Rename file F.txt ask Oh File.txtos.rename (' f.txt ', ' file.txt ')

Remove method

You can delete the file using the Remove () method, and you need to provide the filename to delete as a parameter.

Grammar:

Os.remove (file_name)

Example:

Import osos.remove (' Stdout.txt ')

  

Iv. Supplemental Content 4.1 various system operations

Note: Although Python provides a variety of functions for stitching directories, the function does not guarantee that the character encoding is not a problem, which can cause a program error. So it's better to splice yourself.

The operation of files, folders (file manipulation functions) in Python involves both the OS module and the Shutil module.

Get the current working directory, that is, the directory path of the current Python script work: OS.GETCWD () returns all files and directory names under the specified directory: Os.listdir () function to delete a file: Os.remove () Delete multiple directories: Os.removedirs (r "C:\python") verifies whether the given path is a file: Os.path.isfile () verifies whether the given path is a directory: Os.path.isdir () Determine if absolute path: os.path.isabs () checks whether the shortcut Os.path.islink (filename) verifies that the given path is really saved: os.path.exists () returns the directory name and file name of a path: o S.path.split () eg os.path.split ('/home/swaroop/byte/code/poem.txt ') Result: ('/home/swaroop/byte/code ', ' poem.txt ') Detach extension: Os.path.splitext () gets the path name: Os.path.dirname () gets the file name: Os.path.basename () Run the shell command: Os.system () Read and SET environment variables: o S.getenv () and os.putenv () give the line terminator used by the current platform: os.linesep Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R ' to indicate the platform you're using: Os.name for Windows , it is ' NT ', and for Linux/unix users, it is ' POSIX ' rename: Os.rename (old, new) create a single directory: Os.makedirs (r "C:\python\test") to create the individual directories: Os.mkdir (" Test ") Get file properties: Os.stat (file) modify file permissions and timestamp: os.chmod (file) terminates the current process: Os.exit () Get File size: os.path.getsize (filename)

  

4.2 Various directory Operations
Os.mkdir ("file") creates a directory copy file: Shutil.copyfile ("Oldfile", "NewFile") Oldfile and NewFile can only be file Shutil.copy ("Oldfile", " NewFile ") Oldfile can only be a folder, NewFile may be a file, or it can be a destination directory Replication folder: Shutil.copytree (" Olddir "," Newdir ") Olddir and Newdir can only be directories, And Newdir must not have a renamed file (directory) os.rename ("Oldname", "newname") file or directory is to use this command to move files (directories) shutil.move ("Oldpos", "Newpos") Delete file Os.remove ("file") Delete directory Os.rmdir ("dir") can only delete empty directory Shutil.rmtree ("dir") empty directory, content directory can be deleted conversion directory Os.chdir ("path") Change path PS: File operation, often with regular expression: Img_dir = Img_dir.replace (' \ \ ', '/')

Python File Operations Summary

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.