文件名是**G20240226* *代表通配
-- coding: utf-8 --
import os
import shutil
import re
def main():
source_directory = “/A”
destination_directory = “/”
try:
file_list = os.listdir(source_directory)
except FileNotFoundError:
print("Error: Source directory '{}' not found.".format(source_directory))
return
for file_name in file_list:
# 使用正则表达式从文件名中提取日期信息
match = re.search(r'G(\d{4})(\d{2})(\d{2})', file_name)
if match:
year, month, day = match.groups()
year = int(year)
month = int(month)
day = int(day)
destination_path = os.path.join(destination_directory, str(year), str(month).zfill(2), str(day).zfill(2))
# 如果目标文件夹不存在,则创建
try:
os.makedirs(destination_path, exist_ok=True)
except OSError as e:
print("Error: Failed to create directory '{}': {}".format(destination_path, e))
continue
try:
# 将文件移动到目标文件夹
shutil.move(os.path.join(source_directory, file_name), destination_path)
print("Moved file '{}' to '{}'.".format(file_name, destination_path))
except IOError as e:
print("Error: Failed to move file '{}': {}".format(file_name, e))
continue
if name == “main”:
main()
以下是python2.7的写法 服务器默认
-- coding: utf-8 --
import os
import shutil
import re
def main():
# 源目录路径
source_directory = “/A”
# 目标根目录路径
destination_directory = “/”
try:
file_list = os.listdir(source_directory)
except OSError:
print("Error: Source directory '{}' not found.".format(source_directory))
return
for file_name in file_list:
# 使用正则表达式从文件名中提取日期信息
match = re.search(r'G(\d{4})(\d{2})(\d{2})', file_name)
if match:
year, month, day = match.groups()
year = int(year)
month = int(month)
day = int(day)
destination_path = os.path.join(destination_directory, str(year), str(month).zfill(2), str(day).zfill(2))
# 如果目标文件夹不存在,则创建
if not os.path.exists(destination_path):
try:
os.makedirs(destination_path)
except OSError as e:
print("Error: Failed to create directory '{}': {}".format(destination_path, e))
continue
try:
# 将文件移动到目标文件夹
shutil.move(os.path.join(source_directory, file_name), destination_path)
print("Moved file '{}' to '{}'.".format(file_name, destination_path))
except IOError as e:
print("Error: Failed to move file '{}': {}".format(file_name, e))
continue
if name == “main”:
main()