python拷貝檔案到U盤
最近在學python。剛好有個想法,不用每次都用滑鼠複製黏貼就把檔案拷貝到我的U盤裡。如果有興趣的還可以寫個守護程序。
下面是程式碼
import win32file
import os
import win32file
import tempfile
import shutil
from win32com.shell import shell, shellcon
'''
檢查系統有多少個盤,並返回最後一個碟符,一般U盤為最後一個。所以返回的是u碟符號。
'''
def getdrives():
drives=[]
sign=win32file.GetLogicalDrives()
drive_all=["A:\\","B:\\","C:\\","D:\\","E:\\","F:\\","G:\\","H:\\","I:\\",
"J:\\","K:\\","L:\\","M:\\","N:\\","O:\\","P:\\","Q:\\","R:\\",
"S:\\","T:\\","U:\\","V:\\","W:\\","X:\\","Y:\\","Z:\\"]
for i in range(25):
if (sign&1<<i):
if win32file.GetDriveType(drive_all[i])==3:
drives.append(drive_all[i])
return drives
def is_UDisk(drives):
UDisk=[]
for item in drives:
try :
free_bytes,total_bytes,total_free_bytes=win32file.GetDiskFreeSpaceEx(item)
if (free_bytes/1024/1024/1024)<17:
UDisk.append(item)
print 'append'
else:
print free_bytes/1024/1024/1024
except :
break
return UDisk
if __name__=="__main__":
drives=is_UDisk(getdrives())
print drives
dir = ''.join(drives)
'''
往裡面拷貝一個檔案
'''
newfile = os.path.join(dir,"中轉站")
print newfile
#shutil.copytree("C:\\Users\\Lenovo\\Desktop\\2017\\","C:\\Users\\Lenovo\\Desktop\\2018\\")
#filename1 = tempfile.mktemp (".txt")
filename1 = os.path.join(newfile,"hello.txt") #需要拷貝的檔案
#filename3 = "C:\\Users\\Lenovo\\Desktop\\2017"
filename3 = os.path.join(newfile,"hello") # 需要拷貝的資料夾
#open (filename1, "w").close ()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2
filename4 = os.path.join(newfile,"bak")
#拷檔案
#檔案已存在時,shellcon.FOF_RENAMEONCOLLISION會指示重新命名檔案
shell.SHFileOperation ((0, shellcon.FO_COPY, filename1, filename2, 0, None, None))
'''
shell.SHFileOperation (
(0, shellcon.FO_COPY, filename1, filename2, shellcon.FOF_RENAMEONCOLLISION, None, None)
)
shell.SHFileOperation (
(0, shellcon.FO_COPY, filename1, filename2, 0, None, None)
)
'''
if os.path.isfile (filename2): print "Success"
#拷目錄
shell.SHFileOperation (
(0, shellcon.FO_COPY, filename3, filename4, 0, None, None)
)
if os.path.isdir (filename4): print "Success"