使用 junuxx 的解决方案,我想出了一种方法来对目录中的所有文件执行此操作。最终代码如下所示
import wx #this is for GUI interfaces i made to interact with the user. aka wxPython
import os
import glob
import shutil
#the above are the needed libraries.
path_to_copy_from=self.textbox.GetValue() #obtain value written in textbox(made with wxPython)
if os.path.exists(path_to_copy_from):
ori_path=os.getcwd()#get working directory of my program
#combine ori_path and temp to create the destination path for files to be copied to
copy_path="{}{}".format(ori_path,temp)
#change working directory to the one specified by user
os.chdir(path_to_copy_from)
#to copy files based on header
header = ""
pst_header="21 42 44 4e "
for self.files in glob.glob("*.*"):
try:
with open(self.files, 'rb') as f:
for i in range(4):
byte = f.read(1)
header += hex(ord(byte))[2:] + " "
if header == pst_header:
shutil.copy(self.files,copy_path)
#the following 2 lines tells the user using a textbox i made earlier that something is happening. made for a textctrl i made with wxPython
self.textbox2.AppendText("Found file with .pst header.\n")
self.textbox2.AppendText("Copied {} to {}. \n".format(self.files,copy_path))
#to change copied file to read only
path_to_file="{}\{}".format(copy_path,self.files)
#set the file as read-only(for my program only, not necessary to have)
os.chmod(path_to_file,0444)
#to remove the string already in header for next iteration
header = ""
#simple exception handling. change as you need
except TypeError, ex:
pass
except IOError, ex:
pass
非常感谢 :)