首页 > 解决方案 > subprocess.run("mv source destnation", shell=True) 给出输出没有这样的文件或目录,即使文件存在

问题描述

我的 Python 脚本中有两个文件路径列表

old_name = ['/home/student-03-e43755ddd684/data/jane_profile_07272018.doc', '/home/student-03-e43755ddd684/data/jane_contact_07292018.csv']

new_name = ['/home/student-03-e43755ddd684/data/jdoe_profile_07272018.doc', '/home/student-03-e43755ddd684/data/jdoe_contact_07292018.csv']

只是名称jane更改了jdoe ,这是我的脚本

#!/usr/bin/env python3
import sys
import subprocess

old_name = ['/home/student-03-e43755ddd684/data/jane_profile_07272018.doc', '/home/student-03-e43755ddd684/data/jane_contact_07292018.csv']

new_name = ['/home/student-03-e43755ddd684/data/jdoe_profile_07272018.doc', '/home/student-03-e43755ddd684/data/jdoe_contact_07292018.csv']

print(old_name)
print(new_name)

for oldname, newname in zip(old_name, new_name):
 subprocess.run("mv oldname newname", shell=True)
 print("done")
                                                                                      

运行后它给我以下mv 命令错误:

mv: cannot stat 'oldname': No such file or directory 即使我的系统目录中有文件

我想重命名,在oldnamenewname一个目录下

我很沮丧,救救我!

标签: pythonsubprocesscommandmv

解决方案


您需要将传递给的字符串中的oldname和替换为具有这些名称的变量的内容。从 Python 3.6 开始,您可以使用例如文字字符串插值,否则您的字符串将按原样解释。newnamesubprocess.run()

将您的呼叫替换subprocess.run()subprocess.run(f"mv {oldname} {newname}", shell=True)

对于早于 3.6 的 Python 版本,请使用.format()subprocess.run("mv {} {}".format(oldname, newname), shell=True)


推荐阅读