Python是否使用shell从变量目录复制变量文件
我有以下python代码,它试图从变量目录Python是否使用shell从变量目录复制变量文件,python,shell,copy,Python,Shell,Copy,我有以下python代码,它试图从变量目录dir复制存储在变量file中的文件。我还尝试将这些变量作为shell变量传递,然后也可以使用shell命令进行复制 这两种都可能吗?那么请修改我的密码 import os import shutil import subprocess dir='somedir' file='somefile' # Now I want to get $dir as a shell variable and copy the file to # my pres
dir
复制存储在变量file
中的文件。我还尝试将这些变量作为shell变量传递,然后也可以使用shell命令进行复制
这两种都可能吗?那么请修改我的密码
import os
import shutil
import subprocess
dir='somedir'
file='somefile'
# Now I want to get $dir as a shell variable and copy the file to
# my present directory
os.system("echo $dir")
os.system("cp $dir/$file .")
# I want to copy dir/file to the present directory
shutil.copy(dir/file,file) # Following shutil.copy(src,dest) format
shutil.copyfile(dir/file,file)
您可以在Python中简单地执行此操作,如下所示:-
import os
import shutil
dir = 'somedir'
file = 'somefile'
file_to_copy = dir + "/" + file
current_location = os.getcwd()
shutil.copy(file_to_copy, current_location)
现在,位置
somedir
中的文件somefile
将被复制到当前目录位置。可能的重复;字符串格式是否有其他副本?可能的副本不要使用os.system
复制文件。为什么要使用一个依赖于平台的解决方案,而您可以直接使用python呢?无论如何,您的shutil.copy(dir/file,file)
的问题是dir/file
无效。你不能分割字符串。使用os.path.join
将它们组合成文件路径。使用字符串格式os.system(“echo${}”.format(dir))os.system(“cp${}/${}.”.format(dir,file))
更多信息