Working with files
File (file descriptor) in Python is object (as everything else)
Opening file:
f = open(<path>[, mode="<modificator>"][, encoding="utf-8"])
Modificators:
r
– read only (default method)r+
– read and writew
– write (with flushing) (>
in shell)a
– appending (>>
in shell)b
– binary mode
Basic operations
Reading:
f.read(N)
– read N bytes (into string)f.readline()
– read one line (with separator)f.readlines()
– read all file in a list
f.close()
– closing file (Python closes it on exit)Writing:
f.write(text)
– write string to file (w/o closing)f.writelines(lines)
– write list of strings to filef.flush()
– sync buffer to disk (w/o closing file)
Changing position:
From
Python 3.2
: In text files (those opened without a"b"
in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end withseek(0, 2)
).
f.tell()
– returns the file’s current positionf.seek(N, [whence=0])
– shift N bytes from the beginning wherewhence
(direction) can be:0
(from beginning)1
(from current position)2
(from the end)
Example:
Here we are using so-called "context managers" - via *with as" keywords. This allows us to not worry about closing the file descriptor after block of with-as code.
🪄 Code:
📟 Output:
🪄 Code:
Last updated