python+Mosh网课笔记09标准库

部署运行你感兴趣的模型镜像

 太久没写python代码了,学机器学习重新拾起python,笔记比较简陋。

参考:mosh python网课

目录

一、Files

path-文件操作

path-文件夹操作

文件内容读取与编辑

ZIP

CSV

JSON


一、Files

path-文件操作

  • 创建路径的两种方式。一种\\,一种r \
from pathlib import Path

Path("D:\\pythonProject")
Path(r"D:\pythonProject")

from pathlib import Path

path = Path("ecommerce/sales.py")  # 相对路径,前面省略的是当前文件所在的文件夹路径。
print(path.exists())  # 判断文件是否存在。
print(path.is_file())  # 判断是否是文件。
print(path.is_dir())  # 判断是否是文件夹。
print(path.name) #返回文件名字。
print(path.stem)  # 返回文件名字,无扩展名。
print(path.suffix)  # 返回文件扩展名,即类型。
print(path.parent) #返回文件所在的文件夹名字

path = path.with_suffix(".txt")  # 修改文件后缀名。
print(path)


"""打印
True
True
False
sales.py
sales
.py
ecommerce
ecommerce\sales.txt
"""

文件删除

path = Path("ecommerce/__init__.py")

path.unlink()  # Remove this file or link. 运行后,文件被删除。

path-文件夹操作

from pathlib import Path

path = Path("ecommerce")

print(path.exists())  # 文件夹是否存在
print(path.mkdir())  # Create a new directory at this given path.
path.rmdir()  # Remove this directory. The directory must be empty.
path.rename("ecommerce2")

iterdir()

# path.iterdir()返回文件夹下的所有文件和文件夹
for p in path.iterdir():
    print(p)
#可以包装到list中。
path = [p for p in path.iterdir()]
print(path)

path = [p for p in path.iterdir() if p.is_dir()] #返回是文件夹的。

py_files = [p for p in path.glob("*.py")] #返回是.py类型文件的。
print(py_files)

文件内容读取与编辑

print(path.read_text())  # 读取文件内容,打印出来。

path.write_text(".....")  # 文件原来的内容被删除,修改成该内容。

 内容拷贝

#方法一
from pathlib import Path

source = Path("ecommerce/__init__.py")
target = Path()/"__init__.py"

target.write_text(source.read_text())



#方法二
import shutil
shutil.copy(source, target)

ZIP

from pathlib import Path
from zipfile import ZipFile

zip = ZipFile("files.zip", "w") #在当前文件夹下生成files.zip文件。


# 把ecommerce文件夹压缩到files.zip中。
with ZipFile("files.zip", "w") as zip:
    for path in Path("ecommerce").rglob("*.*"):
        zip.write(path)

CSV

import csv

#加入newline=""可写入无换行。
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["transaction_id", "product_id", "price"])
    writer.writerow([1000, 1, 2])
    writer.writerow([1000, 2, 20])


#读取。
import csv

with open("data.csv") as file:
    reader = csv.reader(file)
    print(list(reader))


with open("data.csv") as file:
    reader = csv.reader(file)
    for row in reader:  #一行是一个list打印出来。
        print(row)

JSON

写入

import json
from pathlib import Path

movies = [
    {"id": 1, "title": "Terminator", "year": 1989},
    {"id": 2, "title": "Kindergarten", "year": 1999},
]

data = json.dumps(movies) #将python编码成json字符串
Path("movies.json").write_text(data)   #写入。

读取

import json
from pathlib import Path

data = Path("movies.json").read_text()
movies = json.loads(data)
print(movies)

剩下的SQLite,Date,Random values,emails等用到再学。 SQLite在视频30min处。

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

### Python Mosh 教程笔记 #### 函数定义与调用 函数是一段可重复使用的代码块,用于执行特定的任务。在 Python 中,可以使用 `def` 关键字来定义函数。 ```python def greet(name): """ 打印问候语。 参数: name (str): 被问候人的名字。 """ print(f"Hello, {name}!") ``` 此函数接受一个参数并打印一条消息[^1]。 #### 条件判断 条件结构允许程序基于不同情况做出不同的行为。Python 使用 `if`, `elif`, 和 `else` 语句实现条件逻辑: ```python age = 20 if age >= 18: print("成年人") elif age < 13: print("儿童") else: print("青少年") ``` 这段代码会根据年龄变量的值输出相应的描述[^2]。 #### 循环结构 循环使得能够多次执行一段代码直到满足某个条件为止。常见的两种形式为 `for` 循环和 `while` 循环: ```python # For loop example fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) # While loop example count = 0 while count < 5: print(count) count += 1 ``` 这些例子展示了如何遍历列表以及通过计数器控制循环次数. #### 文件操作 处理文件是编程中的基本需求之一,在 Python 中可以通过内置模块轻松完成读写文件的操作: ```python with open('example.txt', 'w') as file: file.write('这是一个测试') with open('example.txt', 'r') as file: content = file.read() print(content) ``` 这里展示了一个简单的创建新文本文件并向其中写入字符串的过程;接着再次打开该文件以只读模式读取其内容.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值