如何在Python中读取和写入文件

304 阅读8分钟

Python 程序可以从文件中读取信息,也可以向文件中写入数据。虽然普通的变量是在程序运行时存储数据的好方法,但如果你想在程序结束后访问这些数据,你需要把它保存到文件中。从文件中读取数据使你能够处理广泛的信息,而向文件中写入数据则使用户在下次运行程序时能够继续他们的工作。你可以从文件中读取数据,将文本写入文件,甚至将Python结构如列表存储在数据文件中。


从文件中读出

要从一个文件中读取,你的程序需要打开该文件,然后读取文件的内容。你可以一次性读取整个文件的内容,或者逐行读取文件。该 **with**语句可以确保程序在访问完文件后正确关闭文件。

一次性读取整个文件

首先,我们在 Python 项目的目录下有一个文本文件,这样我们就可以对它进行操作。这只是一个简单的文件,用记事本创建,有一些基本的文本。
python text file

filename = 'pythonfile.txt'
with open(filename) as file_object:
    contents = file_object.read()
print(contents)

python file read output

那是什么 **with**关键字?该 **with**关键字是一个上下文管理器。它就像一个处理文件的快捷方式,因为它为你自动处理打开和关闭文件的问题。例如,如果你需要使用一个文件,你将需要打开该文件,并在你完成工作后记得关闭它。语句 **with**open语句为你解决了这个问题。

在 **with**上下文中,我们使用 **open()**函数来打开文件并返回相应的文件对象。如果文件无法被打开,就会抛出一个 OSError。使用我们现在可用的文件对象,我们可以使用 **read()**方法来读取该文件。这个方法从文件中返回指定的字节数,默认值是 **-1**这意味着读取整个文件。

显示文件的属性和特性

filename = 'pythonfile.txt'
with open(filename) as file_object:
    contents = file_object.read()
print(contents)

print('The filename is: ' + file_object.name)
print('The mode is: ' + file_object.mode)

attributes and properties of the file

逐行读取一个文件

读取文件的另一个选择是逐行进行。下面是如何做到这一点的。

filename = 'pythonfile.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line)

python loop over file

这一次,我们看到了很多额外的空白点。这是为什么呢?原因是,从文件中读出的每一行在行尾都有一个换行符。使用 **print()**函数添加了自己的换行符。为了解决这个问题,我们可以使用 **rstrip()**方法,该方法在打印到屏幕上时删除多余的空行。

filename = 'pythonfile.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())

python rstrip example

迭代过程中修改输出

当你在一个文件上逐行迭代输出时,如果你愿意,你可以在每次迭代时采取行动。这里我们有一个文本文件,内容如下。
python replace method

这段代码将遍历该文件的每一行,如果发现 "西班牙语 "就替换为 "墨西哥语"。

file_object = open('replace.txt', 'r')
print('File Contentsn' + file_object.read())
file_object.seek(0)

print('nRevised Output')
for line in file_object:
    revised = line.replace('Spanish', 'Mexican')
    print(revised.rstrip())
file_object.close()

python replace method on iteration

上面的代码使用了一个我们还没有看到的新方法,即 **seek()**方法。seek()方法使用一个指针来跟踪我们在文件中的位置。写入和读取都会移动寻址指针,如果我们在写入或读取文件数次后想要读取该文件,我们必须将寻址指针设回零。我们可以通过运行 seek() 方法或在我们的代码中关闭和重新打开文件来做到这一点。

将这些行存储在一个列表中

在这段代码中,我们可以看到如何将一个文件读入一个列表变量。通过打印出来,我们看到文件的内容确实是一个列表。我们还看到了如何在列表上进行循环以打印出文件的内容。

filename = 'pythonfile.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
print(lines)
for line in lines:
    print(line.rstrip())

python read file into list


写入文件

你可以将 **'w'**参数给 **open()**函数来告诉 Python 你想写到一个文件。如果文件已经存在,这将擦除文件中的任何东西,所以要小心不要覆盖任何你想保留的数据。

创建并写入文件

filename = 'anotherfile.txt'
with open(filename, 'w') as file_object:
    file_object.write('Writing data to a file!')

python w open example

向一个文件写入多行内容

filename = 'anotherfile.txt'
with open(filename, 'w') as file_object:
    file_object.write('This is line one!n')
    file_object.write('This is line two.n')

python multi line file write

向文件追加内容

传递 **'a'**参数告诉 Python 你想追加到一个现有文件的末尾。注意这一次,我们仍然有上一个例子中文件中的数据。这就是附录行为的作用。

filename = 'anotherfile.txt'
with open(filename, 'a') as file_object:
    file_object.write('Appending this line to the file.n')
    file_object.write('Appending another line to the file.n')

python append file example


文件路径

这个 **open()**函数在正在执行的程序所在的同一目录下寻找文件。要从一个子文件夹中打开一个文件,你可以使用相对路径。如果你愿意,你也可以使用绝对路径。

从子文件夹中打开一个文件

file_path = 'subfolder/valuabledata.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())

python Open a file from a subfolder

用绝对路径打开一个文件

file_path = 'C:pythonpythonforbeginnerssubfolder\valuabledata.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()
print(lines)

python Opening a file with an absolute path


用JSON存储数据

Python有一个JSON模块,允许你将Python数据结构转储到一个文件中,然后在下次程序运行时从该文件中加载这些数据。JSON 是一种流行的数据格式,几乎在所有的现代编程语言中都使用,所以你可以与其他可能不使用 Python 的人分享这种数据。重要的是,在使用它之前,要确保你试图加载的数据存在,如果不存在,你应该使用异常处理来管理。

使用json.dump()来存储数据

import json
numbers = [3, 6, 9, 12, 15, 18]
filename = 'numbers.json'
with open(filename, 'w') as file_object:
    json.dump(numbers, file_object)

python write json to file

使用json.load()来读取数据

import json
filename = 'numbers.json'
with open(filename) as file_object:
    numbers = json.load(file_object)
print(numbers)

python read json from file

使用FileNotFoundError来管理数据

import json
file_name = 'nonexistent.json'
try:
    with open(file_name) as file_object:
        numbers = json.load(file_object)
except FileNotFoundError:
    message = f'Unable to find file: {file_name}.'
    print(message)
else:
    print(numbers)

python FileNotFoundError example


读取和写入文件不需要 **with**关键字

到目前为止的例子显示了在使用with关键字的情况下读、写和追加数据。下面是在不使用时进行这些文件操作的方法 with.

打开一个文件进行写入,如果不存在就创建它

file_object = open('pythonfile.txt', 'w+')

打开文件以便在结尾处添加文本

file_object = open('pythonfile.txt', 'a+')

在文件中写入几行数据

for i in range(10):
    file_object.write('This is line %drn' % (i + 1))

完成后关闭该文件

file_object.close()

重新打开文件并读取其内容

file_object = open('pythonfile.txt', 'r')

检查以确保文件被打开

使用read()函数来读取整个文件

if file_object.mode == 'r':
    contents = file_object.read()
    print (contents)

readlines()将各个行读入一个列表中

if file_object.mode == 'r':
    file_lines = file_object.readlines()
    for line in file_lines:
        print(line)

在 Python 中使用临时文件

要在你的 Python 程序中使用一个临时文件,你可以导入 temp_file 模块。下面的代码创建了一个临时文件,并将其存储在 temp_file 变量中。然后,我们可以在临时文件中存储一些数据。在这种情况下,我们要保存2020年7月4日的日期,这样我们就不会忘记观看一些烟花。注意,我们必须使用小写字母b。这是为了把字符串变成一个字节对象,因为这是使用tempfile模块时write()方法所期望的。现在回忆一下,当读或写一个文件时,寻址指针会被移动。这就是为什么我们在试图读取临时文件之前将其设置为0。

import tempfile

# Create a temporary file
temp_file = tempfile.TemporaryFile()

# Write to a temporary file
temp_file.write(b'Save the date: 070420')
temp_file.seek(0)

# Read the temporary file
print(temp_file.read())

# Close the temporary file
temp_file.close()

使用ZipFile模块工作

在 Python 中创建和处理文件档案很容易。让我们看几个例子来说明它是如何工作的。我们将处理我们目录中的几个文本文件:ships.txt 和 characters.txt。
text file to archive with python
second text file to archive with python

创建一个 FileArchive.zip 文件

# Zipfile Module
import zipfile

# create a ZipFile object
zip_object = zipfile.ZipFile('FileArchive.zip', 'w')

将两个文件添加到存档中并关闭它

# Add two files to the zip_object
zip_object.write('ships.txt')
zip_object.write('characters.txt')

# close the Zip File
zip_object.close()

列出存档的内容

# Open and List contents
zip_object = zipfile.ZipFile('FileArchive.zip', 'r')
print(zip_object.namelist())
['ships.txt', 'characters.txt']

获取存档中文件的元数据

# Metadata in the zip archive
for meta in zip_object.infolist():
    print(meta)
<ZipInfo filename='ships.txt' filemode='-rw-rw-rw-' file_size=84>
<ZipInfo filename='characters.txt' filemode='-rw-rw-rw-' file_size=59>

#Metadata of a single file in the archive
info = zip_object.getinfo('ships.txt')
print(info)
<ZipInfo filename='ships.txt' filemode='-rw-rw-rw-' file_size=84>

读取存档中的文件

# Read a file in the zip archive
print(zip_object.read('ships.txt').decode("utf-8"))
X-Wing
Millennium Falcon
Y-wing
B-wing
The Ghost
Jedi Starfighter
The Fireball

with zip_object.open('characters.txt') as file_object:
    print(file_object.read().decode("utf-8"))
Bowser
Princess Peach
Toad
Luigi
Wario
Yoshi
Rosalina

从存档中提取单个或多个文件

zip_object.extract('ships.txt')
zip_object.extract('characters.txt')
zip_object.extractall()

如何在Python中读和写文件 摘要

Python提供了处理文件的内置方法。你可以打开文件,向其写入数据,再读回数据,等等。所有你希望对文件做的事情都可以在 Python 中完成。你不需要为了读和写文件而导入一个库。使用 Python 内置的 open 函数来获得一个文件对象是处理文件的第一步。这将返回一个文件对象,我们在本教程的几个例子中看到了这个对象。有几个文件对象的方法和属性可以用来了解你所打开的文件的情况。它们还可以用来操作文件。因此,在本教程中,我们研究了从文件中读出,显示文件的属性,逐行读取文件,在列表中存储文件的行数,向文件写入,向文件写入多行,用JSON存储数据,创建临时文件,以及使用ZipFile模块创建和读取文件档案。