How to use the mv command in Python with subprocess

后端 未结 4 2117
天命终不由人
天命终不由人 2021-02-19 10:39

I have a lot of files in /home/somedir/subdir/ and I\'m trying to move them all up to /home/somedir programmatically.

right now I have this:

subprocess.c         


        
4条回答
  •  面向向阳花
    2021-02-19 11:19

    if you call subprocess that way:

    subprocess.call(["mv", "/home/somedir/subdir/*", "somedir/"])
    

    you're actually giving the argument /home/somedir/subdir/* to the mv command, with an actual * file. i.e. you're actually trying to move the * file.

    subprocess.call("mv /home/somedir/subdir/* somedir/", shell=True)
    

    it will use the shell that will expand the first argument.

    Nota Bene: when using the shell=True argument you need to change your argument list into a string that will be given to the shell.

    Hint: You can also use the os.rename() or shutil.move() functions, along with os.path.walk() or os.listdir() to move the files to destination in a more pythonic way.

提交回复
热议问题