翻译完成

This commit is contained in:
MjSeven 2021-08-02 23:20:40 +08:00
parent 6343fbfb94
commit 1f12540ce3
2 changed files with 132 additions and 139 deletions

View File

@ -1,139 +0,0 @@
[#]: subject: (Reading and writing files with Python)
[#]: via: (https://opensource.com/article/21/7/read-write-files-python)
[#]: author: (Seth Kenlon https://opensource.com/users/seth)
[#]: collector: (lujun9972)
[#]: translator: (MjSeven)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
Reading and writing files with Python
======
Every programming language handles data files differently. Here's how
Python does it.
![Hands on a keyboard with a Python book ][1]
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][2] or [Homebrew][3]. On Windows, you can install Python from [Chocolatey][4].
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:
1. Open
2. Write
3. 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:
1. Open
2. Read
3. 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][5]).
### 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][6], and more. There's also a very nice built-in method for creating and maintaining an [SQLite][7] database and many libraries to handle any number of file formats, including [graphics][8], audio, video, and more.
--------------------------------------------------------------------------------
via: https://opensource.com/article/21/7/read-write-files-python
作者:[Seth Kenlon][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/seth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/python-programming-code-keyboard.png?itok=fxiSpmnd (Hands on a keyboard with a Python book )
[2]: https://opensource.com/article/20/11/macports
[3]: https://opensource.com/article/20/6/homebrew-mac
[4]: https://opensource.com/article/20/3/chocolatey
[5]: https://opensource.com/article/17/10/python-101#idle
[6]: https://opensource.com/article/21/6/parse-configuration-files-python
[7]: https://opensource.com/article/21/2/sqlite3-cheat-sheet
[8]: https://opensource.com/article/19/3/python-image-manipulation-tools

View File

@ -0,0 +1,132 @@
[#]: subject: "Reading and writing files with Python"
[#]: via: "https://opensource.com/article/21/7/read-write-files-python"
[#]: author: "Seth Kenlon https://opensource.com/users/seth"
[#]: collector: "lujun9972"
[#]: translator: "MjSeven"
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "
Python 读写文件
======
每种编程语言处理数据文件的方式都不同Python 是这么干的。
![Hands on a keyboard with a Python book ][1]
有些数据是临时的,它们在应用程序运行时存储在 RAM 中,然后丢弃。但是有些数据是持久的。它们存储在硬盘驱动器上供以后使用,而且它们通常是用户最关心的东西。对于程序员来说,编写代码读写文件是很常见的,但每种语言处理这个任务的方式都有些不同。本文演示了如何使用 Python 处理数据文件。
### 安装Python
在 Linux 上,你可能已经安装了 Python。如果没有你可以从发行版软件仓库安装它。例如在 CentOS 或 RHEL 上:
```bash
$ sudo dnf install python3
```
在 macOS 上,你可以使用 [MacPorts][2] 或 [Homebrew][3] 安装。在 Windows 上,你可以使用 [Chocolatey][4] 安装。
一旦安装了 Python打开你最喜欢的文本编辑器准备好写代码吧。
### 使用 Python 向文件中写入数据
如果你需要向一个文件中写入数据,记住有三个步骤:
1. Open
2. Write
3. Close
这与你在计算机上写代码、编辑照片或执行其他操作时使用的步骤完全相同。首先,打开要编辑的文档,然后进行编辑,最后关闭文档。
在 Python 中,过程是这样的:
```python
f = open('example.txt', 'w')
f.write('hello world')
f.close()
```
这个例子中,第一行以**写**模式打开了一个文件,然后用变量 `f` 表示,我使用了 `f` 是因为它在 Python 代码中很常见,但其他任意有效变量名也能正常工作。
在打开文件时,有不同的模式:
* **w** 代表写入
* **r+** 代表可读可写
* **a** 表示追加
第二行表示向文件中写入数据,本例写入的是纯文本,但你可以写入任意类型的数据。
最后一行关闭了文件。
### 使用 'with' 语法写入数据
有一种简短的方法可以写入数据,对于快速的文件交互很有用。它不会使文件保持打开状态,所以你不必记得调用 **close()** 函数。相反,它使用 **with** 语法:
```python
with open('example.txt', 'a') as f:
    f.write('hello open source')
```
### 使用 Python 读取数据
如果你或你的用户需要通过应用程序需要向文件中写入一些数据,然后你需要使用它们,那么你就需要读取文件了。与写入类似,逻辑一样:
1. Open
2. Read
3. Close
同样的,这个逻辑反映了你一开始使用计算机就已经知道的内容。阅读文档,你可以打开、阅读,然后关闭。在计算机术语中,”打开“文件意味着将其加载到内存中。
实际上,一个文本文件内容肯定不止一行。例如,你需要读取一个配置文件、游戏保存的数据或乐队下一首歌曲的歌词,正如你打开一本实体书时,你不可能立刻读完整本书,代码也只能解析已经加载到内存中的文件。因此,你可能需要遍历文件的内容。
```python
f = open('example.tmp', 'r')
for line in f:
    print(line)
f.close()
```
示例的第一行表示使用 **读** 模式打开一个文件,然后文件交由变量 `f` 表示,但就像你写数据一样,变量名是任意的。`f` 并没有什么特殊的,它只是单词 "file" 的最简表示,所以 Python 程序员会经常使用它。
在第二行,我们使用了 `line`,另一个任意变量名,用来表示 `f` 的每一行。这告诉 Python 逐行迭代文件的内容,并将每一行的内容打印到输出中(在本例中为终端或 [IDLE][5])。
### 使用 'with' 语法读取数据
就像写入一样,使用 `with` 语法是一种更简短的方法读取数据。即不需要调用 **close()** 方法,方便地快速交互。
```python
with open('example.txt', 'r') as f:
    for line in f:
        print(line)
```
### 文件和 Python
使用 Python 有很多方法向文件写入数据,包括用 [JSON、YAML、TOML][6] 等不同的格式写入。还有一个非常好的内置方法用于创建和维护 [SQLite][7] 数据库,以及许多库来处理不同的文件格式,包括[图像][8]、音频和视频等。
--------------------------------------------------------------------------------
via: https://opensource.com/article/21/7/read-write-files-python
作者:[Seth Kenlon][a]
选题:[lujun9972][b]
译者:[MjSeven](https://github.com/MjSeven)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/seth
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/python-programming-code-keyboard.png?itok=fxiSpmnd "Hands on a keyboard with a Python book "
[2]: https://opensource.com/article/20/11/macports
[3]: https://opensource.com/article/20/6/homebrew-mac
[4]: https://opensource.com/article/20/3/chocolatey
[5]: https://opensource.com/article/17/10/python-101#idle
[6]: https://opensource.com/article/21/6/parse-configuration-files-python
[7]: https://opensource.com/article/21/2/sqlite3-cheat-sheet
[8]: https://opensource.com/article/19/3/python-image-manipulation-tools