18.md 3.7 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# Python 文件处理

> 原文: [https://thepythonguru.com/python-file-handling/](https://thepythonguru.com/python-file-handling/)

* * *

于 2020 年 1 月 7 日更新

* * *

我们可以使用文件处理来读写文件中的数据。

## 开启档案

* * *

在读/写之前,您首先需要打开文件。 打开文件的语法是。

```py
f = open(filename, mode)

```

W
wizardforcel 已提交
24
`open()`函数接受两个参数`filename``mode``filename`是一个字符串参数,用于指定文件名及其路径,而`mode`也是一个字符串参数,用于指定文件的使用方式,即用于读取或写入。 `f`是文件处理程序对象,也称为文件指针。
W
init  
wizardforcel 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

## 关闭档案

* * *

读/写完文件后,您需要使用`close()`这样的方法关闭文件,

```py
f.close()  # where f is a file pointer

```

## 打开文件的不同模式是

* * *

| 模式 | 描述 |
| --- | --- |
| `"r"` | 打开文件以只读 |
| `"w"` | 打开文件进行写入。 如果文件已经存在,则在打开之前将清除其数据。 否则将创建新文件 |
| `"a"` | 以追加模式打开文件,即将数据写入文件末尾 |
| `"wb"` | 打开文件以二进制模式写入 |
| `"rb"` | 打开文件以二进制模式读取 |

现在让我们看一些示例。

## 将数据写入文件

* * *

```py
>>> f = open('myfile.txt', 'w')    # open file for writing
>>> f.write('this first line\n')   # write a line to the file
>>> f.write('this second line\n')  # write one more line to the file
>>> f.close()                      # close the file

```

W
wizardforcel 已提交
63
**注意**
W
init  
wizardforcel 已提交
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

`write()`方法不会像`print()`功能那样自动插入新行(`'\n'`),需要显式添加`'\n'`来编写`write()`方法。

## 从文件读取数据

* * *

要从文件读回数据,您需要以下三种方法之一。

| 方法 | Description |
| --- | --- |
| `read([number])` | 从文件中返回指定数量的字符。 如果省略,它将读取文件的全部内容。 |
| `readline()` | 返回文件的下一行。 |
| `readlines()` | 读取所有行作为文件中的字符串列表 |

## 一次读取所有数据。

* * *

```py
>>> f = open('myfile.txt', 'r')
>>> f.read() # read entire content of file at once
"this first line\nthis second line\n"
>>> f.close()

```

将所有行读取为数组。

```py
>>> f = open('myfile.txt', 'r')
>>> f.readlines() # read entire content of file at once
["this first line\n", "this second line\n"]
>>> f.close()

```

只读一行。

```py
>>> f = open('myfile.txt', 'r')
>>> f.readline() # read the first line
"this first line\n"
>>> f.close()

```

## 追加数据

* * *

要附加数据,您需要以`'a'`模式打开文件。

```py
>>> f = open('myfile.txt', 'a')
>>> f.write("this is third line\n")
19
>>> f.close()

```

W
wizardforcel 已提交
125
## 使用`for`循环遍历数据
W
init  
wizardforcel 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

* * *

您可以使用文件指针遍历文件。

```py
>>> f = open('myfile.txt', 'r')
>>> for line in f:
...   print(line)
...
this first line
this second line
this is third line

>>> f.close()

```

## 二进制读写

* * *

W
wizardforcel 已提交
148
要执行二进制 I/O,您需要使用一个名为`pickle`的模块。 `pickle`模块允许您分别使用`load``dump`方法读取和写入数据。
W
init  
wizardforcel 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

## 写入二进制数据

* * *

```py
>> import pickle
>>> f = open('pick.dat', 'wb')
>>> pickle.dump(11, f)
>>> pickle.dump("this is a line", f)
>>> pickle.dump([1, 2, 3, 4], f)
>>> f.close()

```

## 读取二进制数据

* * *

```py
>> import pickle
>>> f = open('pick.dat', 'rb')
>>> pickle.load(f)
11
>>> pickle.load(f)
"this is a line"
>>> pickle.load(f)
[1,2,3,4]
>>> f.close()

```

如果没有更多数据要读取,则`pickle.load()`会引发`EOFError`或文件结尾错误。

W
wizardforcel 已提交
183
在下一课中,我们将学习 python 中的[类和对象](/python-object-and-classes/)
W
init  
wizardforcel 已提交
184 185 186 187

* * *

* * *