Files in Python

Files in Python

>>> t = open(“D:/pliczek.txt”)
>>>

Let’s see the methods:

>>> dir(t)
[‘_CHUNK_SIZE’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘
__enter__’, ‘__eq__’, ‘__exit__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__
getstate__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__iter__’, ‘__le__’, ‘__lt__’,
‘__ne__’, ‘__new__’, ‘__next__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__se
tattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘_checkClosed’, ‘_checkRe
adable’, ‘_checkSeekable’, ‘_checkWritable’, ‘buffer’, ‘close’, ‘closed’, ‘detac
h’, ‘encoding’, ‘errors’, ‘fileno’, ‘flush’, ‘isatty’, ‘line_buffering’, ‘mode’,
 ‘name’, ‘newlines’, ‘read’, ‘readable’, ‘readline’, ‘readlines’, ‘seek’, ‘seeka
ble’, ‘tell’, ‘truncate’, ‘writable’, ‘write’, ‘writelines’]
>>>

Now, let’s see how they work:

>>> t = open(“D:/derek.txt”, mode=’r’)
>>> t.read()
‘We have a new ship\nMurek’
>>>

We can open our file.

>>> t.buffer
<_io.BufferedReader name=’D:/pliczek.txt’>
>>> print(t.buffer)
<_io.BufferedReader name=’D:/pliczek.txt’>
>>> list(t.buffer)
[]
>>>

We can see if something is in the buffer.

>>> t.close()
>>> t.closed
True
>>>

We can close the file.

>>> t.encoding
‘cp1250’
>>>

We can see the encoding for our file.

>>> t.errors
‘strict’
>>>

We can see that the strict mode is set.

>>> t.fileno()
4
>>>

We can see the internal file descriptor (FD) used by the OS library as we working with this file.

>>> t.isatty()
False
>>>

We can see if our file is connected to a terminal or keyboard.

>>> t.flush

We can write data from the buffer to our file.

>>> t.line_buffering
False
>>>

We can see if line buffering is enabled for working with streams.

>>> t.mode
‘w’
>>>

We can see the mode of our file.
>>> t.name
‘D:/pliczek.txt’
>>>

we can see  the name of our file.
>>> t.newlines
>>>
>>> t.readable()
False
>>>

We can know if our file is readable.
>>> t.seekable()
True
>>>

>>> t.tell()
0
>>>

We can see the current position in our file.

>>> t.seek(0)
0
>>> t.tell()
0
>>> t.seek(34)
34
>>> t.tell()
34
>>> t.seek(3400)
3400
>>> t.tell()
3400
>>>

We can set the current position in our file.

>>> t.writable()
True
>>>

We can see if our file is writable.
>>> t.truncate()
0
>>>

We can truncate our file.

>>> t.truncate(3)
3
>>>

We can truncate our file to the position we want.

Leave a comment