python 文件覆盖 os 模块

python file overwriting with os module

我正在编写一个程序,将文件从一个文件夹移动到另一个文件夹。有时我会在此过程中覆盖文件。但是,每当我 运行 文件时,系统都会询问我 "Overwrite C:... (Yes/No/All)"。我希望我的程序始终自动 select "All"。提前谢谢你

import os
from tkinter import *
screen = Tk()
sourceplayers = 'C:\Program Files (x86)\...\players' 
destinationplayers = 'C:\memory\Will\players'
sourceuserdata = ('C:\\Program Files (x86)\...\remote'
destinationuserdata = 'C:\\memory\Will\remote'

def copyout(): 
    os.system ("""xcopy "%s" "%s" """ % (sourceplayers, destinationplayers)) 
    os.system ("""xcopy "%s" "%s" """ % (sourceuserdata, destinationuserdata)) #save


def movein():
    os.system ("""xcopy "%s" "%s" """ % (destinationplayers, sourceplayers))
    os.system ("""xcopy "%s" "%s" """ % (destinationuserdata, sourceuserdata))  

button = Button(screen, text="save", command=copyout)
button1 = Button(screen, text="overwrite", command=movein)
button.pack()
button1.pack()
screen.mainloop()

那是因为您正在使用系统调用来进行移动。您可以使用 os.listdir to list all the files and directories inside the source one, and shutil.move 的组合来进行移动。

根据 TechNet docs,看起来 xcopy 需要 /y 标志 "Suppresses prompting to confirm that you want to overwrite an existing destination file."

我想你会像这样使用它:

os.system ("""xcopy "%s" "%s" /y""" % (sourceplayers, destinationplayers))

您可以将 /y 开关作为 xcopy 命令的一部分传递,以始终覆盖文件,但如果您确实想根据您的问题提供输入(select 全部),请尝试类似https://github.com/pexpect/pexpect

如果你不能使用旗帜。您可以尝试使用 subprocess.Popen 写入标准输入,这应该完全符合您的要求:

from subprocess import PIPE,Popen

p = Popen(["xcopy",sourceplayers, destinationplayers],stdin=PIPE)
p.stdin.write("All\n")
p = Popen(["xcopy",sourceuserdata, destinationuserdata],stdin=PIPE)
p.stdin.write("All\n")

无论哪种方式,你都应该在 os.system 上使用 subprocess 模块,subprocess 是 os.popen、os.system 等的替代品。

如果 /y 适用于所有文件,请使用 subprocess.check_call:

from subprocess import check_call

check_call(["xcopy","/y",sourceuserdata, destinationuserdata])

如果您希望上一个命令 return 在下一个命令 运行 之前在每个调用之间放置一个 p.wait() 以等待进程 return。

如果您要替换文件,则不需要查看 python 之外的内容,您可以使用 shutil.move:

from shutil import move
move(sourceplayers, destinationplayers)