This article will help you understand Python file reading and writing

Release: 2023-07-25 13:49:24
forward
1330 people have browsed it

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)
Copy after login

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()
Copy after login

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' #编码
Copy after login

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

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

四、 文件对象操作

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

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

1. f.read(size)

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

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


str = f.read()
print(str)


f.close()
Copy after login

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

2. f.readline()

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

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

3. f.readlines()

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

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

4. 遍历文件

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

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


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


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

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

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

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

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

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

5. f.write()

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

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


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


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

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))
Copy after login
print(f.read(1))
Copy after login

运行结果:

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!')
Copy after login

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

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

六、总结

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

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!

Related labels:
source:Go语言进阶学习
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Access ModeDescription
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.
##rbTo 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.