Python Notes

Reading data from a file and writing to a file

Creating a file

In Python, to create a file, you need to open it in write mode ('w', 'wb') or append mode ('a', 'ab').

f2 = open("text2.txt", 'w')

The open() function returns a file object.

Without 'b', a text file is created, which is a stream of characters. With 'b' is the file containing the byte stream.

In Python, there is also the 'x' or 'xb' mode. In this mode, it is checked whether there is a file. If a file with this name already exists, it will not be created. In the 'w' mode, the file is recreated, the old one is lost.

>>> f1 = open('text1.txt', 'w')
>>> f2 = open('text1.txt', 'x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'text1.txt'
>>> f3 = open('text1.txt', 'w')

Reading data from a file

If the second argument is not passed to the open() function, the file is treated as a text file and opened for reading.

An attempt to open a non-existent file to read causes an error.

>>> f = open("text10.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'text10.txt'

You can catch an exception by using the try-except operator.

>>> try:
...     f = open("text10.txt")
... except IOError:
...     print ("No file")
... 
No file

To get all the data from a file, you can use the read() method of the file object, after opening the file for reading. In this case, the file object is changed and it will not be possible to retrieve the data from it again.

>>> f = open("text.txt")
>>> f
<_io.TextIOWrapper name='text.txt' mode='r' encoding='UTF-8'>
>>> fd = f.read()
>>> fd1 = f.read()
>>> fd
'Hello\n\tOne\n   Two\nThree Four\nSix!\n'
>>> fd1
''

The read() method can have one argument indicating the number of bytes to read.

>>> f = open("text.txt")
>>> fd = f.read(10)
>>> fd1 = f.read(5)
>>> fd
'Hello\n\tOne'
>>> fd1
'\n   T'

readline() allows to receive data line by line.

>>> f = open("text.txt")
>>> f.readline()
'Hello\n'
>>> f.readline()
'\tOne\n'
>>> f.readline()
'   Two\n'

It takes an argument that is the number of bytes.

>>> f.readline(3)
'Thr'
>>> f.readline(3)
'ee '
>>> f.readline(3)
'Fou'
>>> f.readline(3)
'r\n'
>>> f.readline(5)
'Шесть'
>>> f.readline(5)
'!\n'

readlines() reads the lines and places them in the list.

>>> f = open("text.txt")
>>> fd = f.readlines()
>>> fd
['Hello\n', '\tOne\n', '   Two\n', 'Three Four\n', 'Six!\n']

It accepts the number of bytes, but reads the string to the end.

>>> f = open("text.txt")
>>> fd = f.readlines(3)
>>> fd
['Hello\n']
>>> fd1 = f.readlines(6)
>>> fd1
['\tOne\n', '   Two\n']>

Writing data to a file

You can write data to a file using the write() method, which returns the number of characters written.

>>> f1 = open("text1.txt", 'w')
>>> f1.write("Table, cup.\nBig, small.")
23
>>> a = f1.write("Table, cup.\nBig, small.")
>>> type(a)
<class 'int'>

An opened for writing file can not be read. To do this, you need to close it, and then open it for reading.

>>> f1.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
io.UnsupportedOperation: not readable
>>> f1.close()
>>> f1 = open("text1.txt", 'r')
>>> f1.read()
'Table, cup.\nBig, small.Table, cup.\nBig, small.'

Using the writelines() method, you can write an iteration to a file.

>>> a = [1,2,3,4,5,6,7,8,9,0]
>>> f = open("text2.txt",'w')
>>> f.writelines("%s\n" % i for i in a)
>>> f.close()
>>> open("text2.txt").read()
'1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n'
>>> print(open("text2.txt").read())
1
2
3
4
5
6
7
8
9
0

Changing the position in the file

>>> f = open('text.txt')
>>> f.read()
'Hello\n\tOne\n   Two\nThree Four\nSix!\n'
>>> f.close()
>>> f = open('text.txt')
>>> f.seek(10)
10
>>> f.read()
'\n   Two\nThree Four\nSix!\n'

Binary files

The example of copying of an image:

>>> f1 = open('flag.png', 'rb')
>>> f2 = open('flag2.png', 'wb')
>>> f2.write(f1.read())
446
>>> f1.close()
>>> f2.close()

The struct module allows you to convert data to a binary form and vice versa.

>>> f = open('text3.txt', 'wb')
>>> f.write('3')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface
>>> d = struct.pack('>i',3)
>>> d
b'\x00\x00\x00\x03'
>>> f.write(d)
4
>>> f.close()
>>> f = open('text3.txt')
>>> d = f.read()
>>> d
'\x00\x00\x00\x03'
>>> struct.unpack('>i',d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface
>>> f = open('text3.txt', 'rb')
>>> d = f.read()
>>> d
b'\x00\x00\x00\x03'
>>> struct.unpack('>i',d)
(3,)