九、Python Standard Library
1、Paths
from pathlib import Path
# Windows
Path("C:\\Program Files\\Microsoft")
# Or
Path(r"C:\Program Files\Microsoft")
# Mac
Path("/usr/local/bin")
Path() # Current
Path("ecommerce/__init__.py") # Subfolder
Path() / "ecommerce" / "__init__.py" # Combine: pathlib重载了除法运算符
Path.home() # get the home directory of the current user???
from pathlib import Path
path = Path("ecommerce/__init__.py")
path.exists()
path.is_file()
path.is_dir()
print(path.name)
print(path.stem)
print(path.suffix)
print(path.parent)
path1 = path.with_name("file.txt")
print(path1.absolute())
path2 = path.with_suffix(".txt")
print(path2)
__init__.py
__init__
.py
ecommerce
/Users/XXX/PycharmProjects/pythonProject1/ecommerce/file.txt
ecommerce/__init__.txt
2、Working With Directories
path.iterdir(): get the list of files and directories
from pathlib import Path
path = Path("ecommerce")
for p in path.iterdir():
print(p)
print("========================")
paths = [p for p in path.iterdir()]
print(paths)
print("========================")
paths = [p for p in path.iterdir() if p.is_dir()]
print(paths)
ecommerce/shopping
ecommerce/__init__.py
ecommerce/__pycache__
ecommerce/customer
========================
[PosixPath('ecommerce/shopping'), PosixPath('ecommerce/__init__.py'), PosixPath('ecommerce/__pycache__'), PosixPath('ecommerce/customer')]
========================
[PosixPath('ecommerce/shopping'), PosixPath('ecommerce/__pycache__'), PosixPath('ecommerce/customer')]
from pathlib import Path
path = Path("ecommerce")
py_files = [p for p in path.glob("*.py")]
print(py_files)
print("========================")
py_files = [p for p in path.rglob("*.py")]
print(py_files)
[PosixPath('ecommerce/__init__.py')]
========================
[PosixPath('ecommerce/__init__.py'), PosixPath('ecommerce/shopping/sales.py'), PosixPath('ecommerce/shopping/__init__.py'), PosixPath('ecommerce/customer/__init__.py'), PosixPath('ecommerce/customer/contact.py')]
3、Working With Files
from pathlib import Path
from time import ctime
path = Path("ecommerce/__init__.py")
# path.exists()
# path.rename("init.txt")
# path.unlink()
print(ctime(path.stat().st_ctime))
print(path.read_text())
# path.write_text("...")
# path.write_bytes()
Thu Feb 2 23:54:03 2023
print("Ecommerce initialized")
4、Working with Zip Files
from pathlib import Path
from zipfile import ZipFile
zip = ZipFile("files.zip", "w") # This statement will create this file in our current folder
for path in Path("ecommerce").rglob("*.*"): # All
zip.write(path)
zip.close()
But if something goes wrong here, a few statement might not be called
So we should either use a try finally block
Or the With statement which is shorter and clear
from pathlib import Path
from zipfile import ZipFile
with ZipFile("files.zip", "w") as zip: # This statement will create this file in our current folder
for path in Path("ecommerce").rglob("*.*"): # All
zip.write(path)
from pathlib import Path
from zipfile import ZipFile
# Because we only want to read from it, we're not going to open this in write mode!!!!
with ZipFile("files.zip") as zip:
print(zip.namelist())
['ecommerce/__init__.py', 'ecommerce/shopping/sales.py', 'ecommerce/shopping/__init__.py', 'ecommerce/shopping/__pycache__/sales.cpython-310.pyc', 'ecommerce/shopping/__pycache__/__init__.cpython-310.pyc', 'ecommerce/__pycache__/__init__.cpython-310.pyc', 'ecommerce/customer/__init__.py', 'ecommerce/customer/contact.py', 'ecommerce/customer/__pycache__/contact.cpython-310.pyc', 'ecommerce/customer/__pycache__/__init__.cpython-310.pyc']
from pathlib import Path
from zipfile import ZipFile
# Because we only want to read from it, we're not going to open this in write mode!!!!
with ZipFile("files.zip") as zip:
info = zip.getinfo("ecommerce/__init__.py")
print(info.file_size)
print(info.compress_size)
zip.extractall("extract") # Then we will have this extract directory with the content
30
30
5、Working with CSV Files
comma
import csv
# file = open("data.csv", "w")
# file.close()
with open("data.csv", "w") as file:
writer = csv.writer(file)
writer.writerow(["transaction_id", "product_id", "price"])
writer.writerow([1000, 1, 5])
writer.writerow([1001, 2, 15])
import csv
with open("data.csv") as file:
reader = csv.reader(file)
print(list(reader))
for row in reader:
print(row)
只能得到:
[['transaction_id', 'product_id', 'price'], ['1000', '1', '5'], ['1001', '2', '15']]
Because this reader object has an index or a position that is initially set to the beginning of the file, after list(reader)
, that position goes to the end of the file. That is why we cannot iterate this reader twice
So
import csv
with open("data.csv") as file:
reader = csv.reader(file)
# print(list(reader))
for row in reader:
print(row)
['transaction_id', 'product_id', 'price']
['1000', '1', '5']
['1001', '2', '15']
6、Working with JSON Files
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write.