Python File Operation summary, python File Operation Summary

Source: Internet
Author: User

Python File Operation summary, python File Operation Summary

The importance of file operations for programming languages is self-evident. If data cannot be stored permanently, information technology will lose its meaning.

File Operations include opening files, operating files, and closing files

1. open the file

The function for opening a file in python is open ('filename', mode = 'R', encode = 'None'). The open function returns the file handle by default, we can add, delete, modify, and Query files based on the handle. Assign the handle to the defined variable. If we define the variable as f, f = open ('filename', mode = 'R', encode = 'utf-8 ') or with open ('filename') as f.

Note:

1. When the python interpreter opens a file, it operates the hard disk and requires kernel state to operate the hard disk. Therefore, the python interpreter calls the File Reading interface of the operating system. In windows, the Chinese version uses the GBK encoding table by default. in linux, UTF-8 is used by default. If all files operated are not GBK encoded in windows, the encoding type must be declared in the open function, enable the operating system to use the corresponding encoding rules for decoding and reading to prevent string and garbled characters.

2. There are three main open modes: Read (r), write (w), and append (a). The default mode is read. For details about each mode, see the following.

Ii. close the file

There are two methods to close a file:

1. Use f. close () and f to assign the variable name to the handle returned by open.

2. The program is automatically closed after it is completed. The first method may cause data loss during file write operations. The reason is that when writing data, the data will be saved in the memory first, and the file will be written to the hard disk only when it is closed. If the file is not closed, the software will crash due to exceptions, leading to data loss in the memory, not written to the hard disk. As the first method to disable optimization, use: with open ('filename') as f. With creates a program block and places file operations under the with program block. As a result, the with control block ends and the file is automatically closed.

Syntax:

with open('f1.txt') as f1 , open('f2.txt') as f2:    ......

  

3. Basic Methods for operating file 3.1 file

Method

Function

F. read ([size])

Size is the read length, in bytes

F. readline ([size])

If the size is defined, it is possible that only part of a row is returned.

F. readlines ([size])

Use each row of the file as a member of a list and return the list. In fact, it is implemented by calling readline () cyclically. If the size parameter is provided, size indicates the total length of the read content, that is, it may be read only to a part of the file.

F. write (str)

Write str to a file. write () does not add a linefeed after str.

F. writelines (seq)

Write All seq content to the file. This function is only faithfully written and does not add anything to the end of each line.

F. close ()

Close the file. Python will automatically close the file after a file is not used, but this function is not guaranteed, it is best to develop your own habit of closing. If a file is closed and operated on it, ValueError is generated.

F. flush ()

Write the buffer content to the hard disk to refresh the data in the memory to the silver disk.

F. fileno ()

Returns a long integer "file tag".

F. isatty ()

Whether the file is a terminal device file (in unix)

F. tell ()

Returns the current location of the file operation mark, starting with the file

F. next ()

Return to the next row, and move the operation mark of the file to the next row. When a file is used in a statement such as for... in file, the next () function is called to implement traversal.

F. seek (offset [, whence])

Move the file to the offset position by marking the operation. 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, it is not necessary. If the whence parameter is 0, it indicates that the calculation starts from the beginning, and 1 indicates that the calculation is based on the current position. 2 indicates that the origin is the end of the file. Note that if the file is opened in a or a + mode, the file operation mark will be automatically returned to the end of the file each time the file is written.

F. truncate ([size])

Crop the file to a specified size. The default value is the location marked by the current file operation. If the size is larger than the file size, the file may not be changed depending on the system, or 0 may be used to fill the file with the corresponding size, it may also be added with random content.

3.2 read, create, append, delete, and empty a file. Use python to create a new file with an integer ranging from 0 to 9. Each number occupies one row.
f = open('f.txt','w')for i in range(0,10):    f.write(str(i)+'\n')
f.close()
2. append the file content, 10 random integers from 0 to 9
import randomf = open('f.txt','a')for i in range(0,10):    f.write(str(random.randint(0,9)))f.write('\n')f.close()
3. append the file content, a random integer ranging from 0 to 9, a row of 10 numbers, 10 rows in total
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()
4. Export standard output to a file
import syssys.stdout = open('stdout.txt','w')
5. file read/write

5.1. open the file

F = file (name [, mode [, buffering]) name file name mode option, whether the string buffering is buffered (0 = not buffered, 1 = buffered,> 1 int COUNT = buffer size)
File read/write attributes

File objects have their own attributes and methods. Let's take a look at the file attributes. (+ And B can be combined with other characters to form a mode. For example, if rb is enabled in binary read-only mode, the mode parameter is optional. If not, the default value is r)

(Note: After opening the file, it should be closed in time. You can check the f. closed attribute to check whether the file is closed)

Mode

Function

R

In read-only mode (by default, if the file does not exist, an exception occurs), the pointer of the file will be placed at the beginning of the file.

W

Write-only mode (readable. If a file does not exist, the file is created. If yes, the content is deleted and the file is opened)

A

Append mode (write only. If the file does not exist, create it. If yes, append the content)

R +

Read/write mode (readable, writable, appendable)

B

Open it in binary mode (for example, FTP sends and uploads an ISO image file, which can be ignored in linux. It must be noted when processing a binary file in windows)

W +

Write first and then read (readable, writable, and 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. If a file does not exist, it is created. If yes, It is appended ). If the file already exists, the file pointer is placed at the end of the file. When the file is opened, the append mode is used. If the file does not exist, create a new file for reading and writing.

Rb

Opened in binary read mode. Only files can be read. If the file does not exist, an exception occurs.

Wb

Open in binary write mode. Only files can be written. If the file does not exist, create the file.

AB

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

Rt

Open in text read mode and only read files. If the file does not exist, an exception occurs.

Wt

Open the file in text writing mode and only read the file. If the file does not exist, create the file. If the file exists. Clear the file first, and then open the file.

At

Open the file in text read/write mode and only read the file. If the file does not exist, create the file. If the file exists. Clear the file first, and then open the file.

Rb +

Open in binary read mode. You can read or write files. If the file does not exist, an exception occurs.

Wb +

Open in binary write mode. You can read and write files. If the file does not exist, create the file. If the file exists. Clear the file first, and then open the file.

AB +

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

5.2 close the file

f.close()

When the file is read and written, close the file

Vi. Clear File Content
f.truncate()

Note: This function is only available for files opened in writable mode, such as "r +" "rb +" "w" "wb" "wb + ".

VII. File pointer locating and query

7.1, file pointer:
After the file is opened, its object is saved in f. It will remember the current position of the file to facilitate read and write operations, this location is called a file pointer (a long type of bytes counted from the file header ).

7.2, the location when the file is opened:

Files opened in the Read mode of "r" "r +" "rb +", w "" w + "" wb +,
At the beginning, the file Pointer Points to the header of the file.

7.3, get the file pointer value:

 L = f.tell()

  
7.4. Move the object pointer

If the f. seek (offset, option) option is 0, the file pointer is directed from the file header to the "offset" byte. If option is set to 1, the object pointer is directed to the current position of the object and the "offset" byte is moved backward. If option = 2, the object pointer is directed to the end of the object, and the "offset" byte is moved forward.
8. Read content from a file

8.1. Reading of text files (files opened in rt Mode)

S = f. readline () Return Value: s is a string that reads a row from the file, including the row Terminator. Note: (1) if len (s) = 0, it indicates it has reached the end of the file (2) if it is the last row of the file, there may be no line terminator

8.2. Reading of binary files (files opened in the "rb", "rb +", and "wb +" Mode)

S = f. read (n) Description: (1) if len (s) = 0 indicates that the object has been read to the end of the object (2), the object pointer moves the len (s) byte backward. (3) If the track is broken, an exception may occur.
9. Write a string to the file.
F. write (s) parameter: Description of the string to be written by s: (1) After a file is written, the object pointer moves the len (s) byte backward. (2) If the track is broken or the disk is full, an exception may occur. Returned value: s is a string that reads content from the file.
10. Delete Files
import osos.remove(file)

import os
os.remove('s.txt')
3.3 python two methods for reading file content row by row

Method 1:

for line in open('f.txt'):    print(line)

Method 2:

f =open('f.txt','r')lines =f.readlines()for i in lines:    print(i)
3.4 locate the file

The tell () method tells you the current position in the file. In other words, the next read/write will happen after the beginning of the file so many bytes.

The seek (offset [, from]) method changes the location of the current file. The Offset variable indicates the number of bytes to be moved. The From variable specifies the reference position for starting to move bytes.

  If from is set to 0, it means that the start of the file is used as the reference location for moving byte.

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

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

Example:

# Open a file f then open('f.txt ', 'r +') str_read = f. read (10) print ("read string: % s" % str_read) # Find the current position = f. tell () print ("Current position: % s" % position) # locate the pointer again to the beginning of the file position = f. seek (0, 0) str_read = f. read (10) print ("the re-read string is: % s" % str_read) # close the file f. close () Result: The read string is: 2204513940. The current position is: 10. The read string is: 2204513940.
3.5 Rename and delete an object

The Python OS module provides methods to help you perform file processing operations, such as renaming and deleting files.

To use this module, you must first import it before calling related functions.

Rename () method:

The rename () method requires two parameters: the current file name and the new file name.

Syntax:

os.rename(current_file_name, new_file_name)

Example:

Import ossag renamefile f.txtask, file.txtos.rename('f.txt', 'file.txt ')

Remove Method

You can use the remove () method to delete a file. You need to provide the file name to be deleted as a parameter.

Syntax:

os.remove(file_name)

Example:

import osos.remove('stdout.txt')

  

 

Iv. Additional content 4.1 various system operations

Note: Although python provides functions for splicing directories, the function does not guarantee that character encoding is normal and may cause program errors. Therefore, you 'd better splice them yourself.

Operations on files and folders (file operation functions) in python involve the OS module and the shutil module.

Obtain the current working directory, that is, the directory path of the current Python script: OS. getcwd () returns all files and directory names in the specified directory: OS. the listdir () function is used to delete a file: OS. remove () delete multiple directories: OS. removedirs (r "c: \ python") checks whether the given path is a file: OS. path. isfile () checks whether the given path is a directory: OS. path. isdir () determines whether it is an absolute path: OS. path. isabs () checks for shortcuts to OS. path. islink (filename) checks whether the given path is actually stored: OS. path. exists () returns the directory name and file name of a path: OS. path. split () eg OS. path. split ('/home/swaroop/byte/code/poem.txt') Result: ('/home/swaroop/byte/Code', 'poem.txt') Separation Extension: OS. path. splitext () gets the path: OS. path. get the file name: OS. path. basename () Run shell command: OS. system () reads and sets the environment variable: OS. getenv () and OS. putenv () indicates the row Terminator used by the current platform: OS. linesep Windows uses '\ r \ n', Linux uses' \ n', and Mac uses '\ R' to indicate the platform you are using: OS. name is 'nt 'for Windows, while for Linux/Unix users, it is 'posix' renamed: OS. rename (old, new) creates a multilevel Directory: OS. makedirs (r "c: \ python \ test") to create a single directory: OS. mkdir ("test") gets the file attribute: OS. stat (file): OS. chmod (file) terminates the current process: OS. exit () to get the file size: OS. path. getsize (filename)

  

4.2 various directory operations
OS. mkdir ("file") creates a directory to copy the file: shutil. copyfile ("oldfile", "newfile") both oldfile and newfile can only be files shutil. copy ("oldfile", "newfile") oldfile can only be a folder, newfile can be a file, or a destination directory copy Folder: shutil. copytree ("olddir", "newdir") both olddir and newdir can only be directories, and newdir must not exist in the renamed file (directory) OS. rename ("oldname", "newname") files or directories use this command to move the file (directory) shutil. move ("oldpos", "newpos") deletes the file OS. remove ("file") deletes the directory OS. rmdir ("dir") can only delete empty directories. rmtree ("dir") empty directories and directories with content can be deleted and converted to the OS directory. chdir ("path") for path changing ps: During file operations, the regular expression img_dir = img_dir.replace ('\', '/') is often used ('\\','/')

 

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.