【发布时间】:2023-01-29 19:36:29
【问题描述】:
我只是想将文件复制到同一目录中的新名称 但我越来越丑了FileNotFoundError: [Errno 2] 没有那个文件或目录虽然文件存在!
- 在 linux 和 windows 11 上测试了代码
这是我的示例代码:
import os
import shutil
from pathlib import Path
def check_file_existence(file_path):
result = Path(file_path).is_file()
return result
def copy_and_rename_file(source_file_path, destination_file_path):
shutil.copyfile('source_file_path', 'destination_file_path')
path = os.getcwd()
source = Path('./test_file.txt').absolute()
destination = './new_test_file.txt'
perm = os.stat(source).st_mode
print("current path is {}".format(path))
print("current path content is {}".format(os.listdir(path)))
print("source file absolute path is {}".format(source))
print( check_file_existence(source))
print("File Permission mode:", perm)
copy_and_rename_file(source, destination)
一旦执行,我得到以下结果:
current path is D:\New folder
current path content is ['scratch.py', 'test_file.txt']
source file absolute path is D:\New folder\test_file.txt
True
File Permission mode: 33206
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'source_file_path'
有人可以告诉我问题出在哪里吗?!
【问题讨论】:
-
你引用了
'source_file_path',所以它被解释为只是那个字符串。将函数调用中两个路径的引号去掉,它应该能够找到源路径并正确输出到目标路径。
标签: python copy shutil file-management