0% found this document useful (0 votes)
44 views4 pages

Pytthon1-1 6

This document discusses file input/output (I/O) in Python. It covers opening and closing files, reading and writing text files line-by-line and in full, and processing text files iteratively. Binary file operations like seeking to positions are also mentioned. Key methods for reading and writing include open(), close(), readline(), readlines(), read(), write(), and processing files using a with statement or try-finally block.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views4 pages

Pytthon1-1 6

This document discusses file input/output (I/O) in Python. It covers opening and closing files, reading and writing text files line-by-line and in full, and processing text files iteratively. Binary file operations like seeking to positions are also mentioned. Key methods for reading and writing include open(), close(), readline(), readlines(), read(), write(), and processing files using a with statement or try-finally block.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

File Input/Output
File Input/Ouput (IO) requires 3 steps:

Open the file for read or write or both.


Read/Write data.
Close the file to free the resouces.
Python provides built-in functions and modules to support these operations.

1.1 Opening/Closing a File


open(file, [mode='r']) -> fileObj: Open the file and return a file object. The
available modes are: 'r' (read-only - default), 'w' (write - erase all contents for
existing file), 'a' (append), 'r+' (read and write). You can also use 'rb', 'wb',
'ab', 'rb+' for binary mode (raw-byte) operations. You can optionally specify the
text encoding via keyword parameter encoding, e.g., encoding="utf-8".
fileObj.close(): Flush and close the file stream.
1.2 Reading/Writing Text Files
The fileObj returned after the file is opened maintains a file pointer. It
initially positions at the beginning of the file and advances whenever read/write
operations are performed.

Reading Line/Lines from a Text File


fileObj.readline() -> str: (most commonly-used) Read next line (upto and include
newline) and return a string (including newline). It returns an empty string after
the end-of-file (EOF).
fileObj.readlines() -> [str]: Read all lines into a list of strings.
fileObj.read() -> str: Read the entire file into a string.
Writing Line to a Text File
fileObj.write(str) -> int: Write the given string to the file and return the number
of characters written. You need to explicitly terminate the str with a '\n', if
needed. The '\n' will be translated to the platform-dependent newline ('\r\n' for
Windows or '\n' for Unixes/Mac OS).
Examples
# Open a file for writing and insert some records
>>> f = open('test.txt', 'w')
>>> f.write('apple\n')
>>> f.write('orange\n')
>>> f.write('pear\n')
>>> f.close() # Always close the file
# Check the contents of the file created

# 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()

# Read line-by-line using readline() in a while-loop


>>> f = open('test.txt')
>>> line = f.readline() # include newline
>>> while line:
line = line.rstrip() # strip trailing spaces and newline
# process the line
print(line)
line = f.readline()
apple
orange
pear
>>> f.close()
1.3 Processing Text File Line-by-Line
We can use a with-statement to open a file, which will be closed automatically upon
exit, and a for-loop to read line-by-line as follows:

with open('path/to/file.txt', 'r') as f: # Open file for read


for line in f: # Read line-by-line
line = line.strip() # Strip the leading/trailing whitespaces and newline
# Process the line
# File closed automatically upon exit of with-statement
The with-statement is equivalent to the try-finally statement as follows:

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]

# Verify source file


if not os.path.isfile(fileIn):
print("error: {} does not exist".format(fileIn))
sys.exit(1)

# Verify destination file


if os.path.isfile(fileOut):
print("{} exists. Override (y/n)?".format(fileOut))
reply = input().strip().lower()
if reply[0] != 'y':
sys.exit(1)

# Process the file line-by-line


with open(fileIn, 'r') as fpIn, open(fileOut, 'w') as fpOut:
lineNumber = 0
for line in fpIn:
lineNumber += 1
line = line.rstrip() # Strip trailing spaces and newline
fpOut.write("{}: {}\n".format(lineNumber, line))
# Need \n, which will be translated to platform-dependent newline
print("Number of lines: {}\n".format(lineNumber))

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]

You might also like