304_python_模块1
【摘要】 python内置模块1
模块
# jason模块
data_dict ={"name" : "alex", "age":30}
# data_dic_str = json.dumps(data_dict, ensure_ascii=False)
data_dic_str = json.dumps(data_dict)
print(data_dic_str, type(data_dic_str)) # <class 'str'> #
data_dic_str2 = json.loads( data_dic_str) #{"name": "alex", "age": 30} <class 'str'>
print(data_dic_str2, type(data_dic_str2)) # {'name': 'alex', 'age': 30} <class 'dict'>
# datetime
t2 = datetime.now()
print(t2, type(t2)) # 2022-02-28 15:51:36.889999 <class 'datetime.datetime'>
t3 = t2 - timedelta(hours= 3) #2022-02-28 12:51:36.889999
print(t3)
#time和datetime
时间戳 time
datetime 类型
字符串类型
# str - datetime - time
text = "2022-02-28 12:51:36"
date_time = datetime.strptime(text, "%Y-%m-%d %H:%M:%S") # datetime 类型
time_time = date_time.timestamp() # 转成 timestamp
print(time_time) # 1646023896.0
# time - datetime - str
v1 = time.time()
date_time2 = datetime.fromtimestamp(v1) # 转成 datetime
# print(date_time2, type(date_time2)) #2022-02-28 16:12:41.733975 <class 'datetime.datetime'>
date_time2_str = datetime.strftime(date_time2, "%Y-%m-%d %H:%M:%S") # 转成 string
print(date_time2_str, type(date_time2_str)) #2022-02-28 16:14:45 <class 'str'>
sys模块
sys.path.append 导入文件默认寻找的路径
sys.argv 获取脚本的参数
python demo.py x1 x2
import sys
print(sys.argv)
# ["demo.py"]
# ["demo.py","x1","x2"
shutil模块
``python
import shutil
# 1. 删除文件夹
"""
path = os.path.join(base_path, 'xx')
shutil.rmtree(path)
"""
# 2. 拷贝文件夹(新建目录)
"""
import shutil
shutil.copytree('pearvideo', 'x1')
"""
# 3.拷贝文件
"""
shutil.copy('x1/1745129/cont-1745129-15791216_adpkg-ad_hd.mp4', 'xx')
"""
# 4.文件或文件夹重命名
"""
shutil.move("x.png","xxxx.png")
shutil.move("/Users/wupeiqi/PycharmProjects/CodeRepository/files","/Users/wupeiqi/PycharmProjects/CodeRepository/images")
"""
# 5. 压缩文件
"""
# base_name,压缩后的压缩包文件
# format,压缩的格式,例如:"zip", "tar", "gztar", "bztar", or "xztar".
# root_dir,要压缩的文件夹路径
"""
shutil.make_archive(base_name=r'datafile',format='zip',root_dir=r'files')
# 6. 解压文件
"""
# filename,要解压的压缩包文件
# extract_dir,解压的路径
# format,压缩文件格式
"""
shutil.unpack_archive(filename=r'2021.zip', extract_dir='x2/x3/x4', format='zip')
```
subprocess模块
```python
import subprocess
res = subprocess.getoutput("ls")
print(res)
res = subprocess.check_output("ls -l", shell=True, cwd="/Users/wupeiqi/PycharmProjects/xxx/xxx/xxx")
res_string = res.decode('utf-8')
print(res_string)
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)