从零开始的python基础教程(2)
创始人
2024-05-24 16:04:09
0

九、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 Pathpath = 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 Pathpath = 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 Pathpath = 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 ctimepath = 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 ZipFilezip = ZipFile("files.zip", "w") # This statement will create this file in our current folder
for path in Path("ecommerce").rglob("*.*"): # Allzip.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 ZipFilewith ZipFile("files.zip", "w") as zip:  # This statement will create this file in our current folderfor path in Path("ecommerce").rglob("*.*"):  # Allzip.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 csvwith 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 csvwith 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.

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...