Python3走一个目录并写入该目录中的文件

时间:2016-12-22 00:12:23

标签: python bin

我创建了一个脚本,将我文件的二进制内容写入同一目录中以某个扩展名结尾的其他文件。但是当我这样做时,我遇到了一个问题,当我打开文件并将新文件保存在文件夹中时,它会创建一个新文件。我会举一个例子。里面有一个带有test.py的文件夹,FOLDER1,文件夹里面是一个名为OPTION1的文件夹,里面有文件,bye.sh和hello。当我尝试执行test.py时,我的程序在OPTION1中看到文件bye.sh和hello(hello的二进制数据被复制到bye.sh)并读取它,但是在test.py创建的FOLDER1中创建了一个新文件在FOLDER1中新建一个bye.sh,如何让它覆盖OPTION1中的bye.sh?刚才提到,我正在运行Mac OS X.

代码在这里:

import os
class FileHandler:
    #import all needed modules
    def __init__(self):
        import os
    #Replaces second file with the binary data in file one
    """
   Trys To Check If a File Exists
   If It exists, it will open the file that will be copied in binary form and the output file in reading/writing binary form
   If the input file doesnt exist it will tell the user, then exit the program
   Once the files are open, it reads the input file binary and copies it to the output file
   Then it checks to see if the two binaries match which they should if it all worked correctly, the program will then return true
   The Files are then closed
   If it failed to try it will tell the user the file was skipped
   """
    def replaceBinary(self,file_in="",file_out=""):
        try:
            if(os.path.isfile(file_in)):
                in_obj = open(file_in,"rb") #Opens The File That Will Be Copied
                out_obj = open(file_out,"wb+") #Opens The File That Will Be Written To
                object_data = in_obj.read()#Get Contents of In File
                out_obj.write(object_data)# Write Contents of In File To Out File
                print("SPECIAL FILE:"+file_out)
                print(os.getcwd())
                if out_obj.read() == in_obj.read():
                    print("Its the same...")
                    return True
                print("Done Copying...")
            else:
                print("Usage: Enter an input file and output file...")
                print(file_in+" Doesn't Exist...")
                raise SystemExit
                return False
            in_obj.close()
            out_obj.close()
        except:
            print("File, "+file_out+" was skipped.")
        """
       Procedurally continues down an entire location and all its locations in a tree like manner
       Then For each file found it checks if it matches of the extensions
       It checks a file for the extensions and if it has one of them, it calls the replace binary function
       """
    def WalkRoot(self,file1="",root_folder=""):
        for root,dirs,files in os.walk(root_folder):
            for f in files:
                print(os.path.abspath(f))
                array = [".exe",".cmd",".sh",".bat",".app",".lnk",".command",".out",".msi",".inf",".com",".bin"]
                for extension in array:
                    if(f.endswith(extension)):
                        print("Match|\n"+os.path.abspath(f)+"\n")
                        self.replaceBinary(file1,os.path.abspath(f))
                        break #If The right extension is met skip rest of extensions and move to next file
        print("Done...")



def main():
  thing = FileHandler()
  #path = os.path.join(os.getcwd())
  path = input(str("Enter path:"))
  thing.WalkRoot("Execs/hello","/Users/me/Documents/Test")
main()

谢谢!

1 个答案:

答案 0 :(得分:0)

os.walk()返回的文件列表不包含目录信息。但是,当您浏览列表时,dirpath(您调用root)会更新。引用手册,

  

filenames是dirpath中非目录文件的名称列表。注意   列表中的名称不包含路径组件。获得完整的路径   (以top开头)到dirpath中的文件或目录,执行   os.path.join(dirpath,name)。[1]

因此,要获得顶级目录中文件的正确完整路径,请尝试替换

  

self.replaceBinary(file1的,os.path.abspath则(f))的

  

self.replaceBinary(file1,os.path.join(root,f))

[1] https://docs.python.org/3.5/library/os.html#os.walk