Python-常用基础操作
1. Python-文件/文件夹操作
os.getcwd() # 返回当前工作目录
if os.path.exists(input_path): # 如果input_path路径存在
os.makedirs(input_path, exist_ok=True) # 如果input_path路径不存在,就创建此路径
allfiles = os.listdir(input_path) # 获取input_path路径下所有的文件/文件夹
allfiles.sort() # 按照文件/文件夹名称排序
allfiles = sorted(allfiles) # 按照文件/文件夹名称排序
allimages = glob.glob(os.path.join(input_path, "*.jpg")) # 获取input_path路径下所有以.jpg结尾的图像
name = allimages[0].split('.')[0] # 将allimages的第0个图像名,以.分割成两个字符,取第0个字符
newname = allimages[0].replace(".jpg", ".png") # 将allimages的第0个图像名,后缀名.jpg替换成.png
shutil.copy(allimages[0], cp_path) # 将allimages的第0个图像复制到cp_path路径下
shutil.copytree(cp_path1, cp_path2) # 将cp_path1文件夹内容复制到cp_path2文件夹
shutil.move(cp_path1, cp_path2) # 将cp_path1文件夹内容移动到cp_path2文件夹
shutil.rmtree(cp_path) # 将cp_path文件夹删除
2. Python-压缩/解压文件
-
zip文件
import zipfile
# 将file_list下的文件全部压缩进creep.zip
with zipfile.ZipFile(r"creep.zip", "w") as zip_file:
for file in file_list:
zip_file.write(file)
# 读取creep.zip压缩文件内的文件名
with zipfile.ZipFile("creep.zip", "r") as zip_file:
print(zip_file.namelist())
# 将单个zip.py文件解压到unzip_path路径
with zipfile.ZipFile("creep.zip", "r") as zip_file:
zip_file.extract("zip.py", unzip_path)
# 将所有文件解压到unzip_path路径
with zipfile.ZipFile("creep.zip", "r") as zip_file:
zip_file.extractall(unzip_path)
# 另一种方法
def un_zip(unzip_file):
"""unzip zip file"""
zip_file = zipfile.ZipFile(unzip_file)
if os.path.isdir(unzip_file + "_files"):
pass
else:
os.mkdir(unzip_file + "_files")
for names in zip_file.namelist():
zip_file.extract(names, unzip_file + "_files/")
zip_file.close()
-
gz文件
import gzip
def un_gz(unzip_file):
"""ungz gz file"""
zip_file = unzip_file.replace(".gz", "")
g_file = gzip.GzipFile(unzip_file)
open(zip_file, "w+").write(g_file.read())
g_file.close()
-
tar文件
import os
import tarfile
# 压缩tar文件
tar = tarfile.open('/path/to/your.tar', 'w')
for root, dir, files in os.walk('/path/to/dir/'):
for file in files:
fullpath = os.path.join(root, file)
tar.add(fullpath, arcname=file)
tar.close()
# 解压tar文件
def un_tar(untar_file):
"""untar tar file"""
tar_file = tarfile.open(untar_file)
tar_names = tar_file.getnames()
if os.path.isdir(untar_file + "_files"):
pass
else:
os.mkdir(untar_file + "_files")
for name in tar_names:
tar_file.extract(name, untar_file + "_files/")
tar_file.close()
-
rar文件
import os
import rarfile
def un_rar(file_name):
"""unrar zip file"""
rar = rarfile.RarFile(file_name)
if os.path.isdir(file_name + "_files"):
pass
else:
os.mkdir(file_name + "_files")
os.chdir(file_name + "_files")
rar.extractall()
rar.close()
3. Python-判断List中元素满足某条件
list1 = [1, 2, 3, 4, 5]
# 判断list1中所有元素位于区间[2,4]
print(all(2 <= i <= 4 for i in list1))
# 判断list1中任一元素位于区间[2,4]
print(any(4 <= i <= 8 for i in list1))
4. Python-一维数组0-1插值
# 一个长度为8的一维数组,需要近邻插值成长度为16
array = [0, 1, 0, 1, 1, 1, 0, 0]
# 创建长度为16的全零数组
zero_array = np.zeros(2 * array.shape[0])
# 奇数位置填充
zero_array[::2] = array
# 偶数位置填充
zero_array[1::2] = array

浙公网安备 33010602011771号