Home Backend Development Python Tutorial Detailed explanation of file operations in python3

Detailed explanation of file operations in python3

Mar 25, 2017 am 11:03 AM
python3 File operations Detailed explanation

Steps: Open the file-"Operate the file-"Close the file


Open the file

文件句柄 = open('文件路径', '模式')
Copy after login

Specify the file encoding

文件句柄= open('文件路径','模式',encoding='utf-8')
Copy after login

In order to prevent forgetting to close the file, you can use the context manager to open the file

with open('文件路径','模式') as 文件句柄:
Copy after login

The modes for opening files are:

  • r, read-only mode (default).

  • w, write-only mode. [Unreadable; create if it does not exist; delete the content if it exists;]

  • a, append mode. [Readable; if it does not exist, create it; if it exists, only append the content;]

  • r+, the file can be read and written. [Readable; Writable; Appendable]

  • w+, write and read

"U" means that when reading, you can r \n \r\n is automatically converted to \n (same as r or r+ mode)

  • rU

  • r+U

"b" means processing binary files (such as: FTP sending and uploading ISO image files, Linux can be ignored, Windows needs to be marked when processing binary files)

  • rb

  • ##wb

  • ab


Close file

文件句柄.close()
Copy after login

Operation file:

detach

#占位
Copy after login

fileno (returns file descriptor, used for I/O operations of the underlying operating system)

fid = 文件句柄.fileno()print(fid)
Copy after login

flush (refresh the buffer and write the data in the buffer to the file immediately)

文件句柄.flush()
Copy after login

isatty (determine whether the file is connected to a terminal device and return a Boolean value)

文件句柄.isatty()
Copy after login

read (read the specified number of characters from the file, read all by default)

str = 文件句柄.read()      #读取整个文件
str1 = 文件句柄.read(10)   #读取文件前10个字符
Copy after login

readable (determine whether the file is readable, return a Boolean value)

文件句柄.readable()
Copy after login

readline (each time Read at most one line of data, and the end of each line contains the newline character '\n')

print(文件句柄.readline())   #读取第一行数据print(文件句柄.readline(3))  #读取第二行前3个字符print(文件句柄.readline())   
#读取第二行剩余字符print(文件句柄.readline())   #读取第三行
Copy after login

seek (Move the pointer for file reading. If the file contains Chinese, the moving pointer must be a multiple of 3, otherwise it will An error is reported because one Chinese character is equal to 3 bytes)

文件句柄.seek(6)
Copy after login

seekable (determines whether the file pointer is available and returns a Boolean value)

文件句柄.seekable()
Copy after login

tell (gets the pointer position)

文件句柄.tell()
Copy after login

truncate (truncate, delete the content behind the pointer, and write it to the file, operate in writable mode)

f = open('text.txt','r+',encoding='utf-8')
f.seek(9)   #把指针移动到第9个字节后面(即第3个中文后面)f.truncate()  #把第3个中文后面的字符删除,并写入文件f.close()
Copy after login

writable (determine whether the file is writable, return a Boolean value)

文件句柄.writable()
Copy after login

write (write the string to the file and return the number of characters)

文件句柄.write('字符串')
Copy after login

The above is the detailed content of Detailed explanation of file operations in python3. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks 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)

Can I delete gho files? Can I delete gho files? Feb 19, 2024 am 11:30 AM

A gho file is an image file created by NortonGhost software and used to back up and restore the operating system and data. In some cases, you can delete gho files, but do so with caution. This article will introduce the role of gho files, precautions for deleting gho files, and how to delete gho files. First, let's understand the role of gho files. A gho file is a compressed system and data backup file that can save an image of an entire hard disk or a specific partition. This kind of backup file is usually used for emergency recovery

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

Go Programming Tips: Deleting Contents from a File Go Programming Tips: Deleting Contents from a File Apr 04, 2024 am 10:06 AM

The Go language provides two methods to clear file contents: using io.Seek and io.Truncate, or using ioutil.WriteFile. Method 1 involves moving the cursor to the end of the file and then truncating the file, method 2 involves writing an empty byte array to the file. The practical case demonstrates how to use these two methods to clear content in Markdown files.

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed analysis of C language learning route Detailed analysis of C language learning route Feb 18, 2024 am 10:38 AM

As a programming language widely used in the field of software development, C language is the first choice for many beginner programmers. Learning C language can not only help us establish the basic knowledge of programming, but also improve our problem-solving and thinking abilities. This article will introduce in detail a C language learning roadmap to help beginners better plan their learning process. 1. Learn basic grammar Before starting to learn C language, we first need to understand the basic grammar rules of C language. This includes variables and data types, operators, control statements (such as if statements,

See all articles