Python
/
Storage
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 6
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tree S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Storage Files
The old data is cleared if the files exists If the file doesn't exists a new one is created import os fp = open(file, "w") fp.write("New line 1") fp.close()
FILES
p245 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
p248 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
p251 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")
➥ Questions