常用文件路径切片
因为自己对路径切片这一块不是很熟悉,所以每次用都到处查浪费了不少时间,今天刚好又用到,整理一下:
python
#绝对路径
video_path=r"E:\avfilm\pokes\qw0001.mp4"
# 从绝对路径中提取完整文件名
video_name = os.path.basename(video_path)
# 文件路径提取,用于后面拼接
video_dir = os.path.dirname(video_path)
# 截取文件名的扩展名MP4
video_name_kz = video_name.split(".")[-1]
# 不带扩展名的文件名abc-123
video_name_notkz = os.path.splitext(video_name)[0]
读取txt进行改名
案例1:
python
import os
"""
此程序是一个更改文件名的程序。将文本中的绝对路径的文件名,字母改为小写
"""
def txt_list():
"""
逐行读取txt文件,将其变为一个列表
"""
list_vido_any = []
list_vido_any.clear()
with open('data.txt', 'r', encoding='UTF-8') as file:
# print(file.readline())
for line in file:
line = line.rstrip('\n')
list_vido_any.append(line)
# print(list_vido_any)
return list_vido_any
for old_name in txt_list():
# print(old_name)
now_name = old_name.lower()
# print(now_name)
os.renames(old_name, now_name)
print("更改成功:\n" + old_name + "\n" + now_name + "\n"*2)
案例2:
python
import os
"""
此程序是一个更改文件名的程序。将文本中的绝对路径的文件名,字母改为小写
"""
def txt_list():
"""
逐行读取txt文件,将其变为一个列表
"""
list_vido_any = []
list_vido_any.clear()
with open(r'D:\systemdoc\desk\666\data.txt', 'r', encoding='UTF-8') as file:
# print(file.readline())
for line in file:
line = line.rstrip('\n')
list_vido_any.append(line)
# print(list_vido_any)
return list_vido_any
for old_name in txt_list():
# 得到源文件名和路径
print(old_name)
# 替换其中的文本
new_name = old_name.replace("[动漫][动漫]", "[动漫]")
#执行修改
os.renames(old_name, new_name)
print("更改成功:\n" + old_name + "\n" + new_name + "\n"*2)
遍历目录下的文件(包含子目录)
python
def vido_any():
"""
文件夹下的视频文件,包含子目录 ,显示为绝对路径
"""
list_vido_any = []
for vido in os.walk(os.getcwd()):
for j in vido[2]:
# i[0]是当前文件夹的绝对路径,j是文件名
path = os.path.join(vido[0], j)
s = path.split(".")
ss = s[len(s) - 1]
if ss == "mp4" or ss == "avi" or ss == "wmv" or ss == "vm4":
# print(path)
list_vido_any.append(path)
return list_vido_any
统计点出现的次数
python
def count_char(str, char):
count = 0
for c in str:
if c == char:
count += 1
return count
string = "BLACKED 19.09.02 JIA LISSA AND STACY CRUZ 4K-chongfu_ok.mp4"
character = "."
cishu = count_char(string, character)
print(cishu)