File Operations - Python Programming by Example (2015)

Python Programming by Example (2015)

8. File Operations

This chapter explains how to work with file operations using Python.

8.1 Getting Started

We can work with I/O file using io package, https://docs.python.org/3/library/io.html .

The next step is to build Python application to write and read a file.

8.2 Writing Data Into A File

To write and read a file, we can use io package. In this section, we try to write data into a file.

8.2.1 Creating a File

We can create a file using open() function with parameter "w". If file is exist, it will recreate a file.

If you want to use the existing file, you can pass "a". Parameter "b" is used for binary file.

# create a file.

# If file is existing, it erases and creates a new one

f1 = open('mydoc1', 'w')

# create a file.

# If file is existing, it appends. Otherwise, it creates

f2 = open('mydoc2', 'a')

# binary files

bf1 = open('mydoc3', 'wb')

bf2 = open('mydoc4', 'ab')

8.2.2 Writing Data

Write data into a file, we can use write() function.

for index in range(1, 12):

data = ''

name = 'user ' + str(index-1)

email = 'user' + str(index-1) + '@email.com'

if index == 1:

data = '{0:3s} {1:10s} {2:15s}\n'.format('No', 'Name', 'Email')

else:

data = '{0:3s} {1:10s} {2:15s}\n'.format(str(index-1), name, email)

f1.write(data)

f2.write(data)

bf1.write(data)

bf2.write(data)

8.2.3 Closing a File

If file operations done, you should call close() to close file.

f1.close()

f2.close()

bf1.close()

bf2.close()

8.2.4 Demo

Let's write these scripts for demo.

#####################################

print('creating files...')

# create a file.

# If file is existing, it erases and creates a new one

f1 = open('mydoc1', 'w')

# create a file.

# If file is existing, it appends. Otherwise, it creates

f2 = open('mydoc2', 'a')

# binary files

bf1 = open('mydoc3', 'wb')

bf2 = open('mydoc4', 'ab')

#####################################

# writing data

print('writing data into files...')

for index in range(1, 12):

data = ''

name = 'user ' + str(index-1)

email = 'user' + str(index-1) + '@email.com'

if index == 1:

data = '{0:3s} {1:10s} {2:15s}\n'.format('No', 'Name', 'Email')

else:

data = '{0:3s} {1:10s} {2:15s}\n'.format(str(index-1), name, email)

f1.write(data)

f2.write(data)

bf1.write(data)

bf2.write(data)

#####################################

# close all

print('close files...')

f1.close()

f2.close()

bf1.close()

bf2.close()

Save into a file, called ch08_01.py. Then, run the program.

$ python3 ch08_01.py

Program output:

p8-1

If success, you can open all files to see the content.

A sample of content from mydoc1 file can be seen in Figure below.

p8-2

A sample of content from mydoc3 file can be seen in Figure below.

p8-3

8.3 Reading Data From A File

To read data per line from a file, we use readline() function.

Write these scripts for demo.

import sys

#####################################

print('opening files...')

f1 = open('mydoc1', 'r')

f2 = open('mydoc2', 'r')

bf1 = open('mydoc3', 'rb')

bf2 = open('mydoc4', 'rb')

#####################################

# reading data

def reading_data(f):

while True:

data = f.readline()

if (data == '') or (data == None):

break

sys.stdout.write(data)

print('for mydoc1>>>>>')

reading_data(f1)

print('>>>>>>>>>>>>>>>')

print('for mydoc2>>>>>')

reading_data(f2)

print('>>>>>>>>>>>>>>>')

print('for mydoc3>>>>>')

reading_data(bf1)

print('>>>>>>>>>>>>>>>')

print('for mydoc4>>>>>')

reading_data(bf1)

print('>>>>>>>>>>>>>>>')

#####################################

# close all

print('close files...')

f1.close()

f2.close()

bf1.close()

bf2.close()

Save into a file, called ch08_02.py. Then, run the program.

$ python3 ch08_02.py

Program output:

p8-4