写一个文件自动命名的工具
以下是一个Python实现的文件自动命名工具,它可以在指定的目录中创建新文件,并自动为其命名。
import os
import datetime
def auto_name_file(directory, extension):
now = datetime.datetime.now()
timestamp = now.strftime("%Y%m%d_%H%M%S")
filename = f"{timestamp}.{extension}"
filepath = os.path.join(directory, filename)
with open(filepath, "w") as file:
file.write("")
return filepath
# Example usage
directory = "/path/to/directory"
extension = "txt"
filepath = auto_name_file(directory, extension)
print(f"New file created: {filepath}")
使用方法:
- 将上述代码保存为一个Python脚本(例如
auto_name_file.py)。 - 在需要使用该工具的地方,导入该脚本:
from auto_name_file import auto_name_file。 - 调用
auto_name_file函数,传入需要创建文件的目录和文件扩展名,例如:auto_name_file("/path/to/directory", "txt")。 - 函数将返回新文件的完整路径,可以使用该路径进行后续操作。
该工具的实现原理是利用当前时间戳生成唯一的文件名,并在指定目录中创建新文件。如果需要修改文件名格式或其他细节,可以根据实际需求进行修改
AI 优化版
原文地址:https://www.cveoy.top/t/topic/hwAk 著作权归作者所有。请勿转载和采集!