1.2.6. 输入和输出

To be exhaustive, here are some information about input and output in Python. 由于我们将使用Numpy方法读取和写入文件,你可以在第一次阅读时跳过本章。

我们从文件中写入或读取字符串(其他类型必须转换为字符串)。To write in a file:

>>> f = open('workfile', 'w') # opens the workfile file
>>> type(f)
<type 'file'>
>>> f.write('This is a test \nand another test')
>>> f.close()

To read from a file

In [1]: f = open('workfile', 'r')
In [2]: s = f.read()
In [3]: print(s)
This is a test
and another test
In [4]: f.close()

1.2.6.1. 迭代文件

In [6]: f = open('workfile', 'r')
In [7]: for line in f:
...: print line
...:
This is a test
and another test
In [8]: f.close()

1.2.6.1.1. 文件的模式

  • Read-only: r
  • Write-only: w
    • Note: Create a new file or overwrite existing file.
  • Append a file: a
  • Read and Write: r+
  • Binary mode: b
    • Note: Use for binary files, especially on Windows.