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 [1]:
!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) 94,795,452,416 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 [2]:
[s for s in open('data.txt',encoding='utf-8')]
Out[2]:
['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 [5]:
f=open('outdata.txt','w')
for i in range(3):
f.write(f'This is line {i}\n')
f.close()
In [6]:
!type outdata.txt
This is line 0 This is line 1 This is line 2
We can open the file and read back the data, including the newlines. No encoding needed if the string encoding is ASCII.
In [7]:
for s in open('outdata.txt'):
print(s,end='')
This is line 0 This is line 1 This is line 2