File IO¶

A file is a sequence of bytes with associated metadata. Files are typically stored on persistent media (e.g. flash memory or disks).

The file data.txt contains the three lines:

Hello, world! 🌍
This is the second line.
And one more.
In [8]:
!dir data.txt
!type data.txt
 Volume in drive C is Windows
 Volume Serial Number is 1A85-7D8B

 Directory of C:\Users\Ed\SharedFolder\bcit\4653\notebooks\lectures

2023-05-15  10:54 AM                59 data.txt
               1 File(s)             59 bytes
               0 Dir(s)  293,268,410,368 bytes free
Hello, world! �
This is the second line.
And one more.

The open function returns an iterable object that, by default, returns successive lines from a file. We can read strings by specifying how they are encoded into bytes:

In [9]:
[s for s in open('data.txt',encoding='utf-8')]
Out[9]:
['Hello, world! 🌍\n', 'This is the second line.\n', 'And one more.']

Passing a 'w' as the second argument creates file object whose write method can be used to write to a file:

In [12]:
f=open('outdata.txt','w')

for i in range(5):
    f.write(f'This is line {i}\n')

f.close()
In [13]:
!type outdata.txt
This is line 0
This is line 1
This is line 2
This is line 3
This is line 4

We can open the file and read back the data, including the newlines. No encoding needed if the string encoding is ASCII.

In [15]:
for s in open('outdata.txt'):
    print(s,end='')
This is line 0
This is line 1
This is line 2
This is line 3
This is line 4