请用python 写一个复制文件到指定目录的函数,要忽略该文件的后缀,要考虑目录权限,操作系统是windows,
时间: 2024-05-19 13:17:45 浏览: 8
好的,以下是一个复制文件到指定目录的函数的Python代码,考虑了忽略文件后缀和目录权限的问题:
import shutil
import os
def copy_file_to_dir(src_file, dest_dir):
# Check if source file exists
if not os.path.isfile(src_file):
print("Error: Source file '{}' does not exist.".format(src_file))
return False
# Check if destination directory exists
if not os.path.isdir(dest_dir):
print("Error: Destination directory '{}' does not exist.".format(dest_dir))
return False
# Get the base filename of the source file without the extension
base_filename = os.path.splitext(os.path.basename(src_file))[0]
# Copy the file to the destination directory with the same name but without the extension
dest_file = os.path.join(dest_dir, base_filename)
shutil.copy2(src_file, dest_file)
# Check if the file was successfully copied
if not os.path.isfile(dest_file):
print("Error: Failed to copy source file '{}' to destination directory '{}'.")
return False
print("File '{}' copied to directory '{}' successfully.".format(src_file, dest_dir))
return True
# Example usage:
copy_file_to_dir('C:/path/to/source/file.txt', 'C:/path/to/destination/directory')