python办公

python办公

Working with Paths

1
2
3
4
5
6
7
8
9
10
11
12
13
from pathlib import Path
path = Path("__init__.py")
path.exists() #让文件一直打开着
print(path.is_file()) # 判断该路径是否为文件 true
print(path.is_dir()) # 判断该路径是否为目录 false
print(path.name) # 输出文件名称(包括扩展名)
print(path.stem) # 输出主干名称(不包括扩展名)
print(path.suffix) # 输出扩展名
print(path.parent) # 输出上层目录
path=path.with_name("file.txt") # 修改文件的名称
path=path.with_suffix(".txt") # 修改文杰的扩展名
print(path)
print(path.absolute()) # 输出绝对路径

Working with Directories

1
2
3
4
5
6
7
from pathlib import Path
path = Path("D://")

for p in path.iterdir():
print(p) #输出目录中的文件
paths = [p for p in path.iterdir()]
print(paths)

Working with Files

输出

stat 系统调用时用来返回相关文件的系统状态信息的。

1
2
3
4
from pathlib import Path
path = Path("D://")

print(path.stat())

查看创建时间

1
2
3
4
5
6
7
8
9
from pathlib import Path
from time import ctime
path = Path("D://1.TXT")
path2 = Path("D://")
print(ctime(path2.stat().st_ctime))# Fri Apr 19 08:29:08 2019
print(ctime(path.stat().st_ctime)) # Wed May 20 13:24:21 2020
print(path.read_text()) # My name is Jason
path.write_text("") # 写点东西
path.write_bytes()

文件拷贝

如何把一个文件中的内容拷贝到另一个文件呢

1
2
3
4
5
from pathlib import Path
import shutil
source = Path("D://1.TXT")
target = Path() / "xixi.py"
shutil.copy(source,target)

Working with Zip Files

使用zipfile压缩文件

创建一个zip文件对象,压缩是需要把mode改为‘w’

1
zfile=zipfile.ZipFile("test.zip","w")

将文件写入zip文件中,即将文件压缩

1
zfile.write(r"../test.py")

将zip文件对象关闭

1
zfile.close()

使用 zipfile 解压文件

1
import zipfile

解压

1
2
zfile=zipfile.ZipFile("../test.zip","r")
zfile.extractall()

利用pathlib遍历目录Path().rglob

因为*可以代表任何字符,所以
rglob(‘*.py’) 就代表后缀名为.py的所有文件
rglob(‘*.*‘)就代表不论什么后缀名的所有文件

1
2
3
4
5
6
from pathlib import Path
from zipfile import ZipFile

with ZipFile("files.zip","w") as zip:
for path in Path("D://untitled").rglob("*.*"):
zip.write(path)

Working with CSV Files

写入文件

1
2
3
4
5
6
import csv
with open("data.csv","w",newline='') as file:
writer = csv.writer(file)
writer.writerow (["transaction_id","product_id","price"])
writer.writerow ([1000,1,5])
writer.writerow ([1000,11,52])

读取文件

当我们通过迭代来输出的时候,会输出三个List。上面的迭代已经成功了,那么当我们再次想输出list的时候,就发现仅仅输出一个[]。因为后面没东西了

1
2
3
4
5
6
7
8
9
10
11
12
import csv
with open("data.csv") as file:
reader = csv.reader(file)
for row in reader:
print(row)
print(list(reader))
'''
['transaction_id', 'product_id', 'price']
['1000', '1', '5']
['1000', '11', '52']
[]
'''

但是,当我们先print(list(reader))的时候,再迭代输出的时候,就什么都输出不了。 输出的时候,文件已经读完了,再去读就读不到什么东西。所以只输出一个List

1
2
3
4
5
6
7
8
9
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'], ['1000', '11', '52']]
'''

Working with JSON Files

写入json文件

1
2
3
4
5
6
7
8
9
10
import json

movies = [
{"id":1,"title":"Terminator","year":1989},
{"id":3,"title":"Kindergarten Cop","year":1993}
]

data = json.dumps(movies)
print(data)
#输出一个列表 [{"id": 1, "title": "Terminator", "year": 1989}, {"id": 3, "title": "Kindergarten Cop", "year": 1993}]

读取json文件

1
2
3
4
5
6
7
8
9
10
11
12
import json
from pathlib import Path

data = Path("movies.json").read_text()
movies = json.loads(data)
print(movies)
print(movies[0])
'''
输出:
[{'id': 1, 'title': 'Terminator', 'year': 1989}, {'id': 3, 'title': 'Kindergarten Cop', 'year': 1993}]
{'id': 1, 'title': 'Terminator', 'year': 1989}
'''

Working with Timestamps

输出秒数

1
2
3
4
5
6
7
8
9
10
11
12
import time

def send_emails():
for i in range(10000000):
pass

start = time.time()
send_emails()
end = time.time()
duration = end-start
print(duration)
# 0.14830493927001953

Working with Datetimes

1
2
3
4
5
6
7
8
9
10
11
from _datetime import datetime
import time

dt2 = datetime(2018,1,1)
dt = datetime.now()
print(datetime.strptime("19/01/01","%y/%m/%d")) # 2019-01-01 00:00:00
dt=datetime.fromtimestamp(time.time())
print(dt)# 2020-05-20 14:55:54.447580
print(f"{dt.year}/{dt.month}") # 2020/05
print(dt.strftime("%Y/%m")) # 2020/05
print(dt>dt2) # true

Working with Time Deltas

Time delta就相当于附加在datetime上的时间

1
2
3
4
5
6
7
8
9
10
from _datetime import datetime,timedelta

dt1 = datetime(2018,1,1)+timedelta(days=23,seconds=1000)
print(dt1) #2018-01-24 00:16:40
duration = dt2-dt1
print(duration)# 847 days, 14:53:32.316273
print("days",duration.days)
print("seconds",duration.seconds) # 这算的是14:53:32.316273代表的秒数
print("total seconds",duration.total_seconds())# 这算的是847 days, 14:53:32.316273的秒数
print("")

Generating Random Values

1
2
3
4
5
6
7
8
import random
print(random.random()) # 生成一个0-1之间的随机数
print(random.randint(1,10)) # 生成一个1-10之间的整数
print(random.choice([1,2,3,4]))# 生成列表之间的一个数
print(random.choices([1,2,3,4],k=2)) # 生成两个从列表中选择的数字
print("".join(random.choices( "abcdeusac8ui",k=4)))#生成4个,并合并成一个字符串
print("".join(random.choices( string.ascii_letters+string.digits,k=4)))
# ascii_letters是string类的一个属性,包含了所有大小写字母,通里digits包含了所有数字

Opening the Browser

1
2
3
import webbrowser
print("Deplotment completed")
webbrowser.open("http://google.com")

Sending Emails

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
message = MIMEMultipart()
message["from"] = "Jason"
message["to"] = "目标邮箱"
message["subject"] = "This is a test"

message.attach(MIMEText("Body"))
with smtplib.SMTP(host="smtp.gmail.com",port = 587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.login("邮箱","密码")
smtp.send_message(message)
print("Sent...")
-------------本文结束,感谢您的阅读-------------