alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[910] Copy a file to another directory with a new name in Python

To copy a file to another directory with a new name in Python, you can use the shutil library. Here's how you can do it:

import shutil
# Specify the source file path
source_file = 'path/to/source/file.txt'
# Specify the destination directory
destination_directory = 'path/to/destination/'
# Specify the new name for the copied file
new_file_name = 'new_file.txt'
# Create the full destination path
destination_path = destination_directory + new_file_name
# Copy the file to the destination directory with the new name
shutil.copy2(source_file, destination_path)

In this code, replace 'path/to/source/file.txt' with the path to the source file you want to copy, 'path/to/destination/' with the path to the destination directory, and 'new_file.txt' with the new name you want to assign to the copied file.

The shutil.copy2 function is used to copy the file to the destination with its new name. It preserves file metadata during the copy. If you don't need to preserve metadata, you can use shutil.copy instead:

shutil.copy(source_file, destination_path)

This code will copy the file from the source path to the destination directory with the specified new name. If the destination directory doesn't exist, it will be created.

posted on   McDelfino  阅读(24)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2022-10-17 【753】Transformer模型
2020-10-17 【492】状态转移:初识马尔科夫链
2019-10-17 【443】Tweets Analysis Q&A
2016-10-17 【229】Raster Calculator - 栅格计算器
点击右上角即可分享
微信分享提示