# 读取文件

> 原文： [https://pythonspot.com/read-file/](https://pythonspot.com/read-file/)

您之前已经看过各种类型的数据持有者：整数，字符串，列表。 但是到目前为止，我们还没有讨论如何读取或写入文件。

## 读取文件

您可以使用以下代码读取文件。

该文件必须与程序位于同一目录中，如果不是，则需要指定路径。

```py
#!/usr/bin/env python

# Define a filename.
filename = "bestand.py"

# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
    content = f.readlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
    print(line),

```

代码的第一部分将读取文件内容。 读取的所有行将存储在变量内容中。 第二部分将遍历变量内容中的每一行。

如果您不想读取换行符`"\n"`，则可以将语句`f.readlines()`更改为此：

```py
content = f.read().splitlines()

```

产生此代码：

```py
#!/usr/bin/env python

# Define a filename.
filename = "bestand.py"

# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
    content = f.read().splitlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
print(line)

```

当上面的代码起作用时，我们应该始终测试要打开的文件是否存在。 我们将首先测试文件是否不存在，如果存在，它将读取文件，否则返回错误。 如下面的代码：

```py
#!/usr/bin/env python
import os.path

# Define a filename.
filename = "bestand.py"

if not os.path.isfile(filename):
    print('File does not exist.')
else:
# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
    content = f.read().splitlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
    print(line)

```

[下载 Python 练习](https://pythonspot.com/download-python-exercises/)