Home Backend Development Python Tutorial In-depth understanding of python file reading and writing methods

In-depth understanding of python file reading and writing methods

Mar 17, 2017 pm 05:14 PM
python

1.open

After using open to open a file, you must remember to call the close() method of the fileobject. For example, you can use the try/finally statement to ensure that the file can be closed in the end.

file_object = open('thefile.txt')

try:

all_the_text = file_object.read( )

finally:

file_object.close( )

Note: You cannot put the open statement in the try block because it will appear when the file is opened. When an exception occurs, the file object file_object cannot execute the close() method.

2. Read file

Read text file

input = open('data', 'r')

#The second parameter defaults to r

input = open('data')

Read binary file

input = open('data', 'rb')

Read all content

file_object = open('thefile.txt')

try:

all_the_text = file_object.read( )

finally:

file_object.close( )

Read fixed bytes

file_object = open('abinfile', 'rb')

try:

while True:

chunk = file_object.read(100)

if not chunk:

                                                                                                                                                                                  ​

##Read each line

list

_of_all_the_lines = file_object.

readline

s( )

If the file is Text file, you can also directly traverse the file object to obtain each line:

for line in file_object: process line

3. Write files

Write text files

output = open('data', 'w')

Write binary files

output = open('data', 'wb')

Append writing file

output = open('data', 'w+')

Write data

file_object = open('thefile.txt', 'w')

file_object.write(all_the_text)

file_object .close( )

Write multiple lines

file_object.writelines(list_of_text_strings)

Note that calling writelines to write multiple lines will have a performance impact It is higher than using write to write once.

When processing log files, we often encounter such a situation: the log file is huge, and it is impossible to read the entire file into the memory for processing at one time. For example, it needs to be on a computer with a physical memory of 2GB. Processing a 2GB log file on the machine, we may want to process only 200MB of its content at a time.

In

Python

, the built-in File object directly provides a readlines(sizehint)

function

to accomplish such a thing. Take the following code as an example:

file = open('test.log', 'r')sizehint = 209715200 # 200M

position

= 0lines = file.readlines(sizehint)while not file.tell() - position < 0: position = file.tell() lines = file.readlines(sizehint)

Every time the readlines(sizehint) function is called, approximately 200MB of data will be returned, and all The returned data must be complete row data. In most cases, the number of bytes of the returned data will be slightly larger than the value specified by sizehint (except when the readlines(sizehint) function is called for the last time). Normally, Python will automatically adjust the user-specified sizehint value to an integer multiple of the internal cache size. file is a special type in python, which is used to operate external files in python programs. Everything in Python is an object, and file is no exception. File has file methods and attributes. Let's first look at how to create a file object:

file(name[, mode[, buffering]])

The file() function is used to create a file object, which has an alias open() may be more vivid, they are built-in functions

. Let’s take a look at its parameters. Its parameters are all passed in the form of

string

. name is the name of the file.

mode is the open mode. The optional values ​​are r w a U, which represent read (default) and write. Add modes that support various line breaks. If you open a file in w or a mode, if the file does not exist, it will be created automatically. In addition, when using w mode to open an existing file, the content of the original file will be cleared, because the initial file operation mark is at the beginning of the file. If you perform a write operation at this time, the original content will undoubtedly be deleted. Erase it. Due to historical reasons, the newline character has different modes in different systems. For example, in Unix it is a \n, but in Windows it is '\r\n'. Opening a file in U mode supports all newline modes. In other words, '\r' '\n' '\r\n' can represent a newline, and there will be a tuple used to store the newline characters used in this file. However, although there are many modes for line breaks, when reading python, they are always replaced by \n. After the mode character, you can also add the two signs + b t, which respectively indicate that the file can be read and written at the same time and the file can be opened in binary mode or text mode (default).

buffering If it is 0, it means no buffering; if it is 1, it means "line buffering"; if it is a number greater than 1, it means the size of the buffer, which should be in bytes.

The file object has its own properties and methods. Let’s first look at the attributes of file.

closed #Mark whether the file has been closed, rewritten by close()

encoding #File encoding

mode #Open mode

name #File name

newlines #The newline mode used in the file is a tuple

softspace #boolean type, usually 0, which is said to be used for print

File reading and writing methods:

F.read([size]) #size is the length of the read, in bytes.

F.readline([size ])

#Read a line. If size is defined, it is possible to return only part of a line

F.readlines([size])

#Read each line of the file Acts as a member of a list and returns the list. In fact, it is implemented internally by calling readline() in a loop. If the size parameter is provided, size represents the total length of the read content, which means that only a part of the file may be read.

F.write(str)

#Write str to the file, write() will not add a newline character after str

F.writelines( seq)

#Write all the contents of seq to the file. This function also just writes faithfully, without adding anything after each line.

Other methods of file:

F.close()

#Close the file. Python will automatically close a file after it is no longer used. However, this function is not guaranteed. It is best to develop the habit of closing it yourself. If a file is operated on after it is closed, a ValueError will be generated

F.flush()

#Write the contents of the buffer to the hard disk

F.fileno()

#Returns a long integer "file label"

F.isatty()

#Whether the file is a terminal device file ( In unix systems)

F.tell()

#Returns the current position of the file operation mark, with the beginning of the file as the origin

F.next()

#Return to the next line and move the file operation flag to the next line. 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 operation mark to the offset position. This offset is generally calculated relative to the beginning of the file, and is generally a positive number. But this is not necessarily the case if the whence parameter is provided. whence can be 0 to start calculation from the beginning, and 1 to calculate from the current position as the origin. 2 means the calculation is performed with the end of the file as the origin. It should be noted that if the file is opened in a or a+ mode, the file operation mark will automatically return to the end of the file every time a write operation is performed.

F.truncate([size])

#Cut the file to the specified size. The default is to cut to the position of the current file operation mark. If size is larger than the file size, depending on the system, the file may not be changed, the file may be padded to the corresponding size with 0, or some random content may be added.


The above is the detailed content of In-depth understanding of python file reading and writing methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How to train PyTorch model on CentOS How to train PyTorch model on CentOS Apr 14, 2025 pm 03:03 PM

Efficient training of PyTorch models on CentOS systems requires steps, and this article will provide detailed guides. 1. Environment preparation: Python and dependency installation: CentOS system usually preinstalls Python, but the version may be older. It is recommended to use yum or dnf to install Python 3 and upgrade pip: sudoyumupdatepython3 (or sudodnfupdatepython3), pip3install--upgradepip. CUDA and cuDNN (GPU acceleration): If you use NVIDIAGPU, you need to install CUDATool

How is the GPU support for PyTorch on CentOS How is the GPU support for PyTorch on CentOS Apr 14, 2025 pm 06:48 PM

Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

How to choose the PyTorch version under CentOS How to choose the PyTorch version under CentOS Apr 14, 2025 pm 02:51 PM

When selecting a PyTorch version under CentOS, the following key factors need to be considered: 1. CUDA version compatibility GPU support: If you have NVIDIA GPU and want to utilize GPU acceleration, you need to choose PyTorch that supports the corresponding CUDA version. You can view the CUDA version supported by running the nvidia-smi command. CPU version: If you don't have a GPU or don't want to use a GPU, you can choose a CPU version of PyTorch. 2. Python version PyTorch

How to operate distributed training of PyTorch on CentOS How to operate distributed training of PyTorch on CentOS Apr 14, 2025 pm 06:36 PM

PyTorch distributed training on CentOS system requires the following steps: PyTorch installation: The premise is that Python and pip are installed in CentOS system. Depending on your CUDA version, get the appropriate installation command from the PyTorch official website. For CPU-only training, you can use the following command: pipinstalltorchtorchvisiontorchaudio If you need GPU support, make sure that the corresponding version of CUDA and cuDNN are installed and use the corresponding PyTorch version for installation. Distributed environment configuration: Distributed training usually requires multiple machines or single-machine multiple GPUs. Place

How to install nginx in centos How to install nginx in centos Apr 14, 2025 pm 08:06 PM

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.

See all articles