search
HomeBackend DevelopmentPython TutorialThis article will help you understand Python file reading and writing


1. What is a file?

The file is to store some storage, so that it can be used directly the next time the program is executed without having to make a new copy, saving time and effort.


2. How to open the file?

Python has a built-in open() method that can read and write files.

Using the open() method to operate a file is like stuffing an elephant into the refrigerator. It can be divided into three steps, one is to open the file, the other is to operate the file, and the third is to close the file.

open syntax

The return value of the open() method is a file object, which can be assigned to a variable (file handle).

The basic syntax format is:

f = open(filename, mode)

Note:

In Python , all objects with read and write methods can be classified as file types. All file type objects can be opened using the open method and ended with the close method.

filename: A string value containing the name of the file you want to access, usually a file path.

mode: There are many modes for opening files. The default is read-only mode r.

Example:

# 打开一个文件
f = open("1.txt", "w")
f.write("Python 是一种非常好的语言。\nPython!!\n")
# 关闭打开的文件
f.close()

Run result:

in 1 Python is a very good language for writing .txt files. Python.

This article will help you understand Python file reading and writing

3. Access mode

Through a table, learn about the commonly used reading and writing modes of Python

##Open a file for writing only enter. If the file already exists, it is overwritten. If the file does not exist, create a new file. ##a##Open a file in binary format only for writing. If the file already exists, it is overwritten. If the file does not exist, create a new file. ##abr w

如果要读取非UTF-8编码的文件,需要给open()函数传入encoding参数。

例如,读取GBK编码的文件:

>>> f = open('gbk.txt', 'r', encoding='gbk')
>>> f.read()
'GBK' #编码

遇到有些编码不规范的文件,可能会抛出UnicodeDecodeError异常,这表示在文件中可能夹杂了一些非法编码的字符。遇到这种情况,可以提供errors参数,表示如果遇到编码错误后如何处理。

f = open('gbk.txt', 'r', encoding='gbk', errors='ignore')

四、 文件对象操作

用open方法打开一个文件,将返回一个文件对象。这个对象内置了很多操作方法。

下面打开了一个f文件对象(1.txt)。对文件对象进行相关的操作。

1. f.read(size)

读取一定大小的数据, 然后作为字符串或字节对象返回。size是一个可选的数字类型的参数,用于指定读取的数据量。当size被忽略了或者为负值,那么该文件的所有内容都将被读取并且返回。

f = open("1.txt", "r")


str = f.read()
print(str)


f.close()

如果文件体积较大,请不要使用read()方法一次性读入内存,而是read(312)这种一点一点的读。

2. f.readline()

从文件中读取一行n内容。换行符为'\n'。如果返回一个空字符串,说明已经已经读取到最后一行。这种方法,通常是读一行,处理一行的情况下使用。

f = open("1.txt", "r")
str = f.readline()
print(str)
f.close()

3. f.readlines()

将文件中所有的行,一行一行全部读入一个列表内,按顺序一个一个作为列表的元素,并返回这个列表。readlines方法会一次性将文件全部读入内存,所以也存在一定的弊端。但是它有个好处,每行都保存在列表里,可随意存取。

f = open("1.txt", "r")
a = f.readlines()
print(a)
f.close()

4. 遍历文件

实际情况中,我们会将文件对象作为一个迭代器来使用。

# 打开一个文件
f = open("1.txt", "r")


for line in f:
    print(line, end='')


# 关闭打开的文件
f.close()

这个方法很简单, 不需要将文件一次性读出,但是同样没有提供一个很好的控制,与readline方法一样只能前进,不能回退。

几种不同的读取和遍历文件的方法比较:

如果文件很小,read()一次性读取最方便;

如果不能确定文件大小,反复调用read(size)比较保险;

如果是配置文件,调用readlines()最方便。普通情况,使用for循环更好,速度更快。

5. f.write()

使用write()可以完成向文件写入数据。

# 打开一个文件
f = open("/tmp/foo.txt", "w")


f.write("Python 是一种非常好的语言。\n我喜欢Python!!\n")


# 关闭打开的文件
f.close()

6. f.tell()

返回文件读写指针当前所处的位置,它是从文件开头开始算起的字节数。一定要注意了,是字节数,不是字符数。

7. f.seek()

如果要改变位置指针的位置, 可以使用f.seek(offset, from_what)方法。seek()经常和tell()方法配合使用。

from_what的值,如果是0表示从文件开头计算,如果是1表示从文件读写指针的当前位置开始计算,2表示从文件的结尾开始计算,默认为0,例如:

offset:表示偏移量。

  • seek(x,0) :从起始位置即文件首行首字符开始移动 x 个字符。

  • seek(x,1) :表示从当前位置往后移动x个字符。

  • seek(-x,2):表示从文件的结尾往前移动x个字符。

例:

f = open("1.txt", "rb+")
f.write(b"1232312adsfalafds")


print(f.tell())




print(f.seek(5))


print(f.read(1))


print(f.seek(-3, 2))
print(f.read(1))

运行结果:

This article will help you understand Python file reading and writing


8. f.close()

关闭文件对象。当处理完一个文件后,调用f.close()来关闭文件并释放系统的资源。文件关闭后,如果尝试再次调用该文件对象,则会抛出异常。忘记调用close()的后果是数据可能只写了一部分到磁盘,剩下的丢失了,或者更糟糕的结果。


五、 with关键字

with关键字用于Python的上下文管理器机制。为了防止open这一类文件打开方法,在操作过程出现异常或错误,或者最后忘了执行close方法,文件非正常关闭等可能导致文件泄露、破坏的问题。

Python提供了with这个上下文管理器机制,保证文件会被正常关闭。不需要再写close语句。注意缩进。

with open('test.txt', 'w') as f:    f.write('Hello, world!')

with支持同时打开多个文件(文件都是随机创建的):

with open('1') as obj1, open('2','w') as obj2:    s=obj1.read()    obj2.write(s)

六、总结

本文基于Python基础,使用Python语言。介绍了有关Python文件操作的知识点,从文件的基本概念入手 ,通过一个个小项目的演示,对常用的读写模式,文件对象操作方法,以及在实际应用中需要注意的问题,都做了详细的讲解。希望帮助你更好的学习Python。

Access Mode Description
r ##Open the file read-only. The file pointer will be placed at the beginning of the file. (default mode).
##w
##Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, new content will be written after existing content. If the file does not exist, create a new file for writing.
##rb To open a file in binary format use Read only. The file pointer will be placed at the beginning of the file. This is the default mode.
##wb
##To open a file in binary format use In addition. If the file already exists, the file pointer will be placed at the end of the file. In other words, new content will be written after existing content. If the file does not exist, create a new file for writing.
Open a file for reading and writing . The file pointer will be placed at the beginning of the file.
Open a file for reading and writing . If the file already exists, it is overwritten.If the file does not exist, create a new file.
a Open a file for reading and writing . If the file already exists, the file pointer will be placed at the end of the file. The file will be opened in append mode. If the file does not exist, a new file is created for reading and writing.
##rb To open a file in binary format use To read and write. The file pointer will be placed at the beginning of the file.
wb To open a file in binary format use To read and write. If the file already exists, it is overwritten. If the file does not exist, create a new file.
ab To open a file in binary format use In addition. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, a new file is created for reading and writing.

The above is the detailed content of This article will help you understand Python file reading and writing. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.