Python
/
Storage
- 1 Language 9
-
Hello World
-
Variables
-
Functions
-
Conditional
-
Operators
-
While
-
Turtle
-
Script Mode
-
Debugging
- 2 Strings 6
-
Slice
-
Raw Strings
-
Regex
-
Validation
-
Config
-
Escape
- 3 Collections 5
-
Lists
-
Dictionaries
-
Efficiency
-
Tuples
-
References
- 4 Functions 5
-
Recursion
-
Factorial
-
Modulus
-
Reassignment
-
Approximate
- 5 Storage 8
-
Files
-
Databases
-
Pipes
-
With open
-
Shelve
-
Zip
-
Csv
-
Json
- 6 Class 4
-
Definition
-
Attributes
-
Functional
-
Methods
- 7 Goodies 5
-
Conditional Expression
-
List Comprehension
-
Generator
-
Named Tuple
-
Modules
- 8 Applications 5
-
Pythagora
-
Palindrome
-
Binary Search
-
Conway Game
-
Coin Flip
- 9 Scheduler 4
-
Time
-
Multithreading
-
Subprocess
-
Logging
- 10 Packages 2
-
Clipboard
-
Ocr
/
Files
➟
➟
Last update: 19-11-2021
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 github Storage