Pytthon1-1 6
Pytthon1-1 6
File Input/Output
File Input/Ouput (IO) requires 3 steps:
# Open the file created for reading and read line(s) using readline() and
readlines()
>>> f = open('test.txt', 'r')
>>> f.readline() # Read next line into a string
'apple\n'
>>> f.readlines() # Read all (next) lines into a list of strings
['orange\n', 'pear\n']
>>> f.readline() # Return an empty string after EOF
''
>>> f.close()
# Open the file for reading and read the entire file via read()
>>> f = open('test.txt', 'r')
>>> f.read() # Read entire file into a string
'apple\norange\npear\n'
>>> f.close()
try:
f = open('path/to/file.txt')
for line in f:
line = line.strip()
# Process the line
finally:
f.close()
Example: Line-by-line File Copy
The following script copies a file into another line-by-line, prepending each line
with the line number.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
file_copy: Copy file line-by-line from source to destination
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Usage: file_copy <src> <dest>
"""
import sys
import os
def main():
# Check and retrieve command-line arguments
if len(sys.argv) != 3:
print(__doc__)
sys.exit(1) # Return a non-zero value to indicate abnormal termination
fileIn = sys.argv[1]
fileOut = sys.argv[2]
if __name__ == '__main__':
main()
1.4 Binary File Operations
[TODO] Intro
fileObj.tell() -> int: returns the current stream position. The current stream
position is the number of bytes from the beginning of the file in binary mode, and
an opaque number in text mode.
fileObj.seek(offset): sets the current stream position to offset bytes from the
beginning of the file.
For example [TODO]