PROGRAMMING

m9/ PYTHON
REMEMBERS




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.
 
fp = open("/var/www/python/myfile.txt", "w")
fp.write("My new line")
fp.close()

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.
 
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()
... 1 lines
 
Os    (2/2)

OS

p248 ! The os module provides functions for working with files and directories.
 
import os
cwd = os.getcwd()
print(cwd) # /var/www/python
path = os.path.abspath("test.py")
print(path) # /var/www/python/test.py
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.
 
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
... 7 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.
 
try:
    fp = open("/var/www/python/") # IsADirectoryError
except:
    print("Error: not a file")

Questions    
Databases

        A B C D E F
🔔
1/3