1.2.6. Input and Output¶
To be exhaustive, here are some information about input and output in Python. Since we will use the Numpy methods to read and write files, you may skip this chapter at first reading.
We write or read strings to/from files (other types must be converted to strings). 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 : f = open('workfile', 'r') In : s = f.read() In : print(s) This is a test and another test In : f.close()
For more details: https://docs.python.org/tutorial/inputoutput.html
126.96.36.199. Iterating over a file¶
In : f = open('workfile', 'r') In : for line in f: ...: print line ...: This is a test and another test In : f.close()
188.8.131.52.1. File modes¶
- Note: Create a new file or overwrite existing file.
- Append a file:
- Read and Write:
- Binary mode:
- Note: Use for binary files, especially on Windows.