REMEMBER PYTHON

MINTE9 2REMEMBER

Last update:   23-07-2021

FILES

p245 Opening a file in write mode clears out old data if the files exists. If the file doesn't exists a new one is created.
 CodeCopy
fp = open("/var/www/python/myfile.txt", "w")
fp.write("My new line")
fp.close()
... 3 lines˄˄˄

FORMAT

p246 ! The argument of the fwrite() must to be string. If you use % the number and the types in a tuple has to match the format.
 CodeCopy
no = 24
fp = open("/var/www/python/myfile.txt", "w")
fp.write(str(33))
fp.write("My file has %d lines" % no)
fp.write("There are 3 numbers: %d %d %d" % (1, 2))
# not enough args
fp.close()
... 7 lines˄˄˄
Os    (2/2)

OS

p248 ! The os module provides functions for working with files and directories.
 CodeCopy
import os
cwd = os.getcwd()
print(cwd) # /var/www/python
path = os.path.abspath("test.py")
print(path) # /var/www/python/test.py
... 5 lines˄˄˄
p250 You can walk through a directory and prints the names of all the files. Os module provides a function similar to this, but more versatile.
 CodeCopy
import os
def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
if os.path.isfile(path):
print(path)
else:
walk(path) # calls itself recursively

walk("/var/www/python")

# /var/www/python/test.py
# /var/www/python/calculator.py
# /var/www/python/words.txt

os.walk("/var/www/python") # built-in walk functions
... 13 lines˄˄˄

Exceptions

p251 ! A lot of things can go wrong when working with files. Handling an error with try statement is called catching an exception.
 CodeCopy
try:
... 4 lines˄˄˄