以下python代码获取文件特定实例的文件路径列表,将它们复制到当前目录中,并在标题中包含路径名:
python3 find.py --copy zz /Users/apt/testdir a.txt
/Users/apt/testdir/d1/a.txt
/Users/apt/testdir/d1/d3/a.txt
/Users/apt/testdir/d1/d3/d4/a.txt
/Users/apt/testdir/d1/d3/d5/a.txt
$ ls zz
Users_apt_testdir_d1_a.txt
Users_apt_testdir_d1_d3_d4_a.txt
Users_apt_testdir_d1_d3_a.txt
Users_apt_testdir_d1_d3_d5_a.txt
一切正常,但我的复制功能:
def copy(f, new_dir):
file_name=str(f[1:])
file_name=file_name.replace('/', "_")
file_path=os.path.join(new_dir, file_name)
shutil.copy(file_path, new_dir)
os.chdir(os.path.abspath(new_dir))
os.rename(list(os.path.split(f))[1], file_name)
FileNotFoundError: [Errno 2] No such file or directory: "zz/['_u_macole_testdir_d1_d3_a.txt', '_u_macole_testdir_d1_d3_d4_a.txt', '_u_macole_testdir_d1_d3_d5_a.txt']
错误非常明显,file
或new_dir
没有好的类型。由于file
是一个列表,因此您需要每次迭代并调用copy
:有点像
for f in file:
copy(f, new_dir)