Python-based file operations

Source: Internet
Author: User

The simplest thing to do with a file operation is to use the print function to output a file to the screen, but it cannot be a file saved to disk, or if it is re-entered with that data.

In Python, however, the necessary functions and methods are provided for the basic operation of the file by default. You can use the file object to do most of the document operations. You can also save data. One of the most common file operations is file read and write operations.

File read/write

Before reading and writing files, we must first understand that the ability to read and write files on disk is provided by the operating system, the modern operating system does not allow ordinary programs to operate the disk directly, so the read-write file is to request the operating system to open a file object (often referred to as a file descriptor), and then, Read the data from this file object (read the file) from the interface provided by the operating system, or write the data to the file object (write file).

Read the file

To open a file object in read-file mode, use Python's built-in open() functions to pass in file names and identifiers

f = open (' E:\LINUX\xx.txt ', ' R ')

The identifier ' R ' means read, so that we have successfully opened a file.

If the file does not exist, it will be an error

The file opens successfully, and next, the calling read() method can read the entire contents of the file at once, and Python reads the contents into memory, represented by an str object:

F.read () ' Hello, world! '

After the completion, and then call the Close () method to close the file, in Python, the system will help you to close the default, but this method is not safe, there is no time certainty, so we do read and write file operation, we must remember to close it

F.close ()
Write a file

Writing and reading files are the same, the only difference being that when a function is called, an identifier is passed in or a write open() - ‘w‘ ‘wb‘ in file or a binary file is written:

f = open (' File stored path ', ' W ') f.write (' Hello, world! ') F.close ()

When we perform the read and write operation of the file, we find that either the file is written or the file is read, and the Close () method is called to close the file. This is due to the security of the file, but also does not preclude the careless person after performing the file read and write, forget to call the Close () method. For this consideration. Python also has a file read and write operation method that does not have to call Close (). is the WITH method.

With open (' File path ', ' W ') as F:    f.write (' Hello, world! ')
Attached: full list of open files in different modes
R opens the file in read-only mode. The pointer to the file will be placed at the beginning of the file. This is the default mode. RB opens a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. r+ open a file for read-write. The file pointer will be placed at the beginning of the file. rb+ opens a file in binary format for read-write. The file pointer will be placed at the beginning of the file. W opens a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. WB opens a file in binary format for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. w+ open a file for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file. wb+ opens a file in binary format for read-write. Overwrite the file if it already exists. If the file does not exist, create a new file. A opens a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to. AB opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written to the existing content. If the file does not exist, create a new file to write to. A + opens a file for read and write. 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. ab+ opens a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to read and write.
File location

The tell () method tells you the current position within the file, in other words, the next read and write occurs 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.

Note: The Foo.txt file is our pre-created file fo = open ("Foo.txt", "r+") str = Fo.read (Ten);p rint ("read string is:", str) # find current position position = Fo.tell ();p Rint ("Current file location:", position) # to reposition the pointer again to the beginning of the file position = Fo.seek (0, 0); str = Fo.read;p rint ("Reread string:", str) # Close Open File Fo.close ()
List functions commonly used by file objects
The File.flush () #刷新文件内部缓冲 directly writes the data of the internal buffer to the file immediately, rather than passively waiting for the output buffer to be written. #最常用的就是进度条实例import sys,timefor i in range: Sys.stdout.write ("*") Sys.stdout.flush () Time.sleep (0.1) File.truncate ( [Size]) #截取文件, the truncated bytes are specified by size, the default is the current file location F.truncate (5) f.write (' Hello World ') f.truncate (5) F.close () Note: This method cannot be performed in "R" mode. In W mode: Clears, then writes, and then truncates in a mode: truncates the contents of the specified position file.read ([size]) directly #从文件读取指定的字节数, if not given or negative, all is read. File.readline ([size]) #读取整行, including the "\ n" character. File.readlines ([Sizehint]) #读取所有行并返回列表, if given sizeint>0, return the sum of approximately sizeint bytes, the actual read value may be larger than sizhint because the buffer needs to be populated.

  

 

  

 

  

Python-based file 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.