Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Python3 operates on files

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Computer file

In a computer system, the set of information stored on the computer with the hard disk as the carrier is called a file. Files can be text documents, pictures, sounds, programs, and other types. When programming, it is often necessary to read and write files. From the programmer's point of view, files can be understood as a continuous sequence of bytes. Data transfer requires the use of byte streams, which can be composed of single bytes or large chunks of data. File types are usually divided into text files and binary files.

File operation

The operation of a file in Python is divided into three steps: first, to open the file, then to read and write to the file, and finally to close the file.

Open the file-open function

You must use Python's built-in open () function to open a file and create a file object before the related methods can call it for reading and writing.

Syntax:

File object = open (file_name [, access_mode] [, buffering])

The details of each parameter are as follows:

The file_name:file_name variable is a string value that contains the name of the file you want to access.

Access_mode:access_mode determines the mode of opening files: read-only, write-only, append, etc. All available values are shown in the complete list below. This parameter is not mandatory, and the default file access mode is read-only (r).

Buffering: if the value of buffering is set to 0, there will be no hosting. If the value of buffering is 1, the line is deposited when the file is accessed. If you set the value of buffering to an integer greater than 1, this is the buffer size of the register area. If you take a negative value, the buffer size of the register area is the system default.

Open a complete list of files in different modes:

The model diagram is as follows:

Properties of the File object

After a file is opened, you have a file object, and you can get all kinds of information about the file.

The following is a list of all the properties related to the file object:

Close the file-the close () method

The close () method of the File object flushes any unwritten information in the buffer and closes the file, after which no further writes can be made.

When a reference to a file object is reassigned to another file, Python closes the previous file. It is a good habit to close the file with the close () method.

Syntax:

FileObject.close ()

Example:

The python code is as follows:

F = open ('exercise .txt', 'wicked grammar encodingwriting utfmur8') # write a file

...

F.close ()

F = open ('exercise .txt', 'ritual design encodingskills utfmur8') # read the file

...

F.close ()

Write data to a file-the write () method

The write () method writes any string to an open file. It is important to note that Python strings can be binary data, not just text.

The write () method does not add a newline character ('\ n') at the end of the string:

Syntax:

FileObject.write (string)

Example:

The python code is as follows:

F = open ('exercise 1. Txtwriting, recording, writing, etc., etc.)

F.write ("I am Chinese\ n")

F.write ("I love my motherland\ n")

F.write ("I love Tiananmen Square in Beijing\ n")

Output result:

Read data from a file

The file.read () method reads a string from an open file. It is important to note that Python strings can be binary data, not just text.

Syntax:

File.read ([count])

Example:

Original file (exercise .txt)

Read the file code as follows:

F = open ('exercise .txt', 'ritual training encodingbirds utfmur8')

Print (f.read (1))

Print (f.read (10))

Output result:

Use file.readline () to read a row of data, which also returns a string example:

The python code is as follows:

F = open ('exercise .txt', 'ritual training encodingbirds utfmur8')

Print (f.readline ())

Output result:

Add a number in file.readline () parentheses to indicate that the string is read as an example:

The python code is as follows:

F = open ('exercise .txt', 'ritual training encodingbirds utfmur8')

Print (f.readline (1))

Output result:

The remaining row data of file.readlines returns an example of a list of strings:

The python code is as follows:

F = open ('exercise .txt', 'ritual training encodingbirds utfmur8')

Print (f.readlines ())

The output is as follows:

File.readlines () adds a number in parentheses to indicate the number of strings read, and the rest of the current line is also read out example 1:

The python code is as follows:

F = open ('exercise .txt', 'ritual training encodingbirds utfmur8')

Print (f.readlines (1)) # indicates the line on which the first string is printed

The output is as follows:

Example 2:

The python code is as follows:

F = open ('exercise .txt', 'ritual training encodingbirds utfmur8')

Print (f.readlines (7)) # means to print the line on which the seventh string is located and all the lines preceding it

The output is as follows:

Note: read () reads all the data and puts it in memory, which takes up a lot of memory and is inefficient. File iterator is recommended here.

File iterator

Starting with Python2.2, iterators and file iterations are introduced to make file operations more efficient and do not require

Call the read () method. To put it simply, an iteration is to read each row of data in a for loop. The sample code is as follows:

The python code is as follows:

F = open ('exercise .txt', 'ritual training encodingbirds utfmur8')

For line in f.readlines ():

Print (line.strip ())

Output result:

Note:

When opening a file in write mode, read operation is not supported. But there are several other modes that can be used to open files using r +, w +, or a + to read and write at the same time.

R + means that the contents of the original file are not cleared and opened in read-write mode, while the newly added data is at the end of the file.

W + means to clear the contents of the original file, open it by writing and reading, and cannot read the contents of the original file.

A + means to move the file pointer to the end of the file, you can continue to write data at the end of the file, reading data is not affected.

File location (file pointer)

The tell () method tells you the current location 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 location of the current file.

The Offset variable represents the number of bytes to move.

The From variable specifies the reference location where the byte starts to move.

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 location is used as the reference location. If it is set to 2, the end of the file will be used as a reference location.

Example:

The python code is as follows:

F = open ('exercise .txt', 'ritual training encodingbirds utfmur8')

Print (f.readline ()) # printed line

F.seek (0) # pointer returns the origin

Print (f.tell ()) # gets the current pointer position

Print (f.readline ()) # print another line

The output is as follows:

Modify a file

1. Load the files into memory and modify them, such as vim.

Note: this method will overwrite the original file, and is not suitable to modify large files, too much system memory consumption, not recommended!

two。 Read the original file, modify the corresponding file, and generate it into the new file. (recommended)

Example:

The python code is as follows:

F = open ('exercise .txt', 'ritual training encodingbirds utfmur8')

F_new = open ('exercise 2.txt recording and recording wishful thinking, encodingwriting writing utfmur8')

For line in f:

If "Song Dynasty: sun Su" in line:

Line = line.replace ("Song Dynasty: sun Su", "Song Dynasty: ci writer") # replace "Sun Su" with "ci writer"

F_new.write (line)

F.close ()

F_new.close ()

The output is as follows:

With usage

There are some tasks that may need to be set up in advance and cleaned up afterwards. Python's with statement provides a very convenient way to handle this scenario. A good example is file processing, where you need to get a file handle, read data from the file, and then close the file handle.

Example:

The python code is as follows:

With open ('exercise .txt', 'ritual, encoding='utf-8') as f:

For line in f.readlines ():

Print (line.strip ())

The output is as follows:

File object built-in method:

The file object is created using the open function, and the following table lists the functions commonly used by the file object:

Summary:

1. This blog refers to the rookie foundation and do-it-yourself writing.

2.python2 is different from python3, here is the file manipulation method of python3.

3.python operation file is a very commonly used method, to often hands-on operation, in order to master knowledge points!

4.python is a language that pays great attention to the indentation format, here affected by blog typesetting, there may be errors in the format, the content is for reference only, it is not recommended to copy, you will understand it by typing a few more times!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report