使用 Python 读写文件
Python 读写

> 
> 每种编程语言处理文件数据的方式不尽相同，Python 是这么干的。
> 
> 
> 


![](/data/attachment/album/202108/05/094700u9kj42rn4jh5h4hr.jpg "Hands on a keyboard with a Python book ")


有些数据是临时的，它们在应用程序运行时存储在内存中，然后丢弃。但是有些数据是持久的。它们存储在硬盘驱动器上供以后使用，而且它们通常是用户最关心的东西。对于程序员来说，编写代码读写文件是很常见的，但每种语言处理该任务的方式都不同。本文演示了如何使用 Python 处理文件数据。


### 安装 Python


在 Linux 上，你可能已经安装了 Python。如果没有，你可以通过发行版软件仓库安装它。例如，在 CentOS 或 RHEL 上：



```
$ sudo dnf install python3

```

在 macOS 上，你可以使用 [MacPorts](https://opensource.com/article/20/11/macports) 或 [Homebrew](https://opensource.com/article/20/6/homebrew-mac) 安装。在 Windows 上，你可以使用 [Chocolatey](https://opensource.com/article/20/3/chocolatey) 安装。


一旦安装了 Python，打开你最喜欢的文本编辑器，准备好写代码吧。


### 使用 Python 向文件中写入数据


如果你需要向一个文件中写入数据，记住有三个步骤：


1. 打开
2. 写入
3. 关闭


这与你在计算机上编码、编辑照片或执行其他操作时使用的步骤完全相同。首先，打开要编辑的文档，然后进行编辑，最后关闭文档。


在 Python 中，过程是这样的：



```
f = open('example.txt', 'w')
f.write('hello world')
f.close()

```

这个例子中，第一行以**写**模式打开了一个文件，然后用变量 `f` 表示，我使用了 `f` 是因为它在 Python 代码中很常见，使用其他任意有效变量名也能正常工作。


在打开文件时，有不同的模式：


* `w` 代表写入
* `r+` 代表可读可写
* `a` 表示追加


第二行表示向文件中写入数据，本例写入的是纯文本，但你可以写入任意类型的数据。


最后一行关闭了文件。


#### 使用 `with` 语法写入数据


对于快速的文件交互，常用有一种简短的方法可以写入数据。它不会使文件保持打开状态，所以你不必记得调用 `close()` 函数。相反，它使用 `with` 语法：



```
with open('example.txt', 'a') as f:
    f.write('hello open source')

```

### 使用 Python 读取数据


如果你或你的用户需要通过应用程序需要向文件中写入一些数据，然后你需要使用它们，那么你就需要读取文件了。与写入类似，逻辑一样：


1. 打开
2. 读取
3. 关闭


同样的，这个逻辑反映了你一开始使用计算机就已知的内容。阅读文档，你可以打开、阅读，然后关闭。在计算机术语中，“打开”文件意味着将其加载到内存中。


实际上，一个文本文件内容肯定不止一行。例如，你需要读取一个配置文件、游戏存档或乐队下一首歌曲的歌词，正如你打开一本实体书时，你不可能立刻读完整本书，代码也只能解析已经加载到内存中的文件。因此，你可能需要遍历文件的内容。



```
f = open('example.tmp', 'r')

for line in f:
    print(line)

f.close()

```

示例的第一行指明使用 **读** 模式打开一个文件，然后文件交由变量 `f` 表示，但就像你写数据一样，变量名是任意的。`f` 并没有什么特殊的，它只是单词 “file” 的最简表示，所以 Python 程序员会经常使用它。


在第二行，我们使用了 `line`，另一个任意变量名，用来表示 `f` 的每一行。这告诉 Python 逐行迭代文件的内容，并将每一行的内容打印到输出中（在本例中为终端或 [IDLE](https://opensource.com/article/17/10/python-101#idle)）。


#### 使用 `with` 语法读取数据


就像写入一样，使用 `with` 语法是一种更简短的方法读取数据。即不需要调用 `close()` 方法，方便地快速交互。



```
with open('example.txt', 'r') as f:
    for line in f:
        print(line)

```

### 文件和 Python


使用 Python 有很多方法向文件写入数据，包括用 [JSON、YAML、TOML](https://opensource.com/article/21/6/parse-configuration-files-python) 等不同的格式写入。还有一个非常好的内置方法用于创建和维护 [SQLite](https://opensource.com/article/21/2/sqlite3-cheat-sheet) 数据库，以及许多库来处理不同的文件格式，包括 [图像](https://opensource.com/article/19/3/python-image-manipulation-tools)、音频和视频等。




---


via: <https://opensource.com/article/21/7/read-write-files-python>


作者：[Seth Kenlon](https://opensource.com/users/seth) 选题：[lujun9972](https://github.com/lujun9972) 译者：[MjSeven](https://github.com/MjSeven) 校对：[turbokernel](https://github.com/turbokernel)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Some data is meant to be temporary, stored in RAM while an application is running, and then forgotten. Some data, however, is meant to be persistent. It's stored on a hard drive for later use, and it's often the stuff that a user cares about the most. For programmers, it's very common to write code to read and write files, but every language handles this task a little differently. This article demonstrates how to handle data files with Python.

## Install Python

On Linux, you probably already have Python installed. If not, you can install it from your distribution's software repository. For instance, on CentOS Stream or RHEL:

`$ sudo dnf install python3`


On macOS, you can install Python from [MacPorts](https://opensource.com/article/20/11/macports) or [Homebrew](https://opensource.com/article/20/6/homebrew-mac). On Windows, you can install Python from [Chocolatey](https://opensource.com/article/20/3/chocolatey).

Once you have Python installed, open your favorite text editor and get ready to code.

## Writing data to a file with Python


If you need to write data to a file, there are three steps to remember:

- Open
- Write
- Close

This is exactly the same sequence of steps you use when writing code, editing photos, or doing almost anything on a computer. First, you open the document you want to edit, then you make some edits, and then you close the document.

In Python, that translates to this process:

```
f = open('example.txt', 'w')
f.write('hello world')
f.close()
```


In this example, the first line opens a file in **write** mode. The file is represented as the variable `f`

, which is an arbitrary choice. I use `f`

because it seems to be common in Python code, but any valid variable name works just as well.

There are different modes in which you can open a file:

**w**to write**r+**to read and write**a**to append only

The second line of the example writes data to the file. The data written in this example is plain text, but you can write any kind of data.

The final line closes the file.

## Writing data using the 'with' syntax

There's a shorter way to write data into a file, and this method can be useful for quick file interactions. It doesn't leave the file open, so you don't have to remember to call the **close()** function. Instead, it uses the **with** syntax:

```
with open('example.txt', 'a') as f:
f.write('hello open source')
```


## Reading data in from a file with Python

If you (or your user, by way of your application) have placed data into a file, and your code needs to retrieve it, then you want to read a file. Similar to writing, the logic is:

- Open
- Read
- Close

Again, this logic flow mirrors what you already know from just using a computer (or a paperback book, for that matter). To read a document, you open it, read it, and then close it. In computer terms, "opening" a file means to load it into memory.

In practice, a text file contains more than one line. For example, maybe your code needs to read a configuration file, saved game data, or the lyrics to your band's next song. Just as you don't read an entire physical book the very moment you open it, your code must parse a file it has loaded into memory. So, you probably need to iterate over the file's contents.

```
f = open('example.tmp', 'r')
for line in f:
print(line)
f.close()
```


In the first line of this example code, you open a file in **read** mode. The file is represented by the variable `f`

, but just like when you open files for writing, the variable name is arbitrary. There's nothing special about `f`

; it's just the shortest possible way to represent the word "file," so it tends to be used a lot by Python programmers.

In the second line, you reserve `line`

, which is yet another arbitrary variable name, to represent each line of `f`

. This tells Python to iterate, line by line, over the file's contents and print each line to your output (in this case, the terminal or [IDLE](https://opensource.com/article/17/10/python-101#idle)).

## Reading a file using the 'with' syntax

As with writing data, there's a shorter method of reading data from files using the **with** syntax. This doesn't require you to call the **call()** function, so it can be convenient for quick interactions.

```
with open('example.txt', 'r') as f:
for line in f:
print(line)
```


## Files and Python

There are more ways to write data to files using Python, and many ways to format text you write to files using [JSON, YAML, TOML](https://opensource.com/article/21/6/parse-configuration-files-python), and more. There's also a very nice built-in method for creating and maintaining an [SQLite](https://opensource.com/article/21/2/sqlite3-cheat-sheet) database and many libraries to handle any number of file formats, including [graphics](https://opensource.com/article/19/3/python-image-manipulation-tools), audio, video, and more.

## 2 Comments