原文: https://pythonspot.com/read-file/

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

读取文件

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

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

  1. #!/usr/bin/env python
  2. # Define a filename.
  3. filename = "bestand.py"
  4. # Open the file as f.
  5. # The function readlines() reads the file.
  6. with open(filename) as f:
  7. content = f.readlines()
  8. # Show the file contents line by line.
  9. # We added the comma to print single newlines and not double newlines.
  10. # This is because the lines contain the newline character '\n'.
  11. for line in content:
  12. print(line),

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

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

  1. content = f.read().splitlines()

产生此代码:

  1. #!/usr/bin/env python
  2. # Define a filename.
  3. filename = "bestand.py"
  4. # Open the file as f.
  5. # The function readlines() reads the file.
  6. with open(filename) as f:
  7. content = f.read().splitlines()
  8. # Show the file contents line by line.
  9. # We added the comma to print single newlines and not double newlines.
  10. # This is because the lines contain the newline character '\n'.
  11. for line in content:
  12. print(line)

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

  1. #!/usr/bin/env python
  2. import os.path
  3. # Define a filename.
  4. filename = "bestand.py"
  5. if not os.path.isfile(filename):
  6. print('File does not exist.')
  7. else:
  8. # Open the file as f.
  9. # The function readlines() reads the file.
  10. with open(filename) as f:
  11. content = f.read().splitlines()
  12. # Show the file contents line by line.
  13. # We added the comma to print single newlines and not double newlines.
  14. # This is because the lines contain the newline character '\n'.
  15. for line in content:
  16. print(line)

下载 Python 练习