minte9
LearnRemember



FILES

Opening a file in write mode clears out old data if the files exists.
 
# Open a file in wrrite mode (default is read)
# 
# The old data is cleared if the files exists.
# If the file doesn't exists a new one is created.
#
# The os module ...
# provides functions for working with files and directories.

import os

dir_path = os.path.dirname(os.path.realpath(__file__))
file = dir_path + "/data/myfile1.txt"

fp = open(file, "w")
fp.write("New line 1 \n")
fp.write("New line 2 \n")
fp.close()

f = open(file)
print(f.read())
    # New line 1 
    # New line 2

Csv

The os module provides functions for working with files and directories.
 
# Write and read csv

import os
import csv

DIR = os.path.dirname(os.path.realpath(__file__))
FILE = DIR + "/data/myfile2.csv"

f = open(FILE, "w")
f.write("c1, c2, c3 \n")
f.write("11, 12, 13 \n")
f.write("12, 22, 23 \n")
f.write("13, 32, 33 \n")
f.close()

f = open(FILE, "r")
assert f.readline().strip() == "c1, c2, c3"
assert f.readline().strip() == "11, 12, 13"


# Walk - Read directories and files

for root, dirs, files in os.walk(DIR + "/data/"):
    for name in files:
        if name.endswith(".csv"):
            path = os.path.join(root, name)
            assert path.endswith(".csv")
            assert name == "myfile2.csv"


# Csv - reader

file = DIR + "/data/myfile2.csv"
data = list(csv.reader(open(file), delimiter=","))
assert data[0] == ['c1', ' c2', ' c3 ']
assert data[1] == ['11', ' 12', ' 13 ']

Exceptions

A lot of things can go wrong when working with files.
 
# Exception
# 
# Handling an error with try statement is called ...
# catching an exception.

try:
    fp = open("/var/www/python/") # Error: not a file
except:
    print("Error: not a file")



  Last update: 97 days ago