python - 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
即使我的系统目录中有文件
我想重命名,在oldname
同newname
一个目录下
我很沮丧,救救我!
解决方案
您需要将传递给的字符串中的oldname
和替换为具有这些名称的变量的内容。从 Python 3.6 开始,您可以使用例如文字字符串插值,否则您的字符串将按原样解释。newname
subprocess.run()
将您的呼叫替换subprocess.run()
为subprocess.run(f"mv {oldname} {newname}", shell=True)
对于早于 3.6 的 Python 版本,请使用.format()
:subprocess.run("mv {} {}".format(oldname, newname), shell=True)
推荐阅读
- python-3.x - 检查数字并转换华氏度
- java - Java不删除文本文件
- firebase - 如何使用 facebook 在 firebase 身份验证中获取用户数据(名称、图像)?
- jquery - jQuery / CSS - 无需遍历所有元素即可检测溢出
- node.js - s3.getObject().promise() 从不返回任何东西
- linux - 如果只有一个帧缓冲区,Xorg 如何管理多个监视器?
- go - Go中的切片分配是否复制内存
- npm - 如何从 3 迁移到 gulp v4?
- observable - 如何比较两个可观察对象中的项目,然后根据 RxJava2 中的匹配项进行过滤?
- c# - 如何创建 .tfignore 文件?