搜索特定类型的文件

时间:2013-11-20 23:32:26

标签: python-2.7

我正在使用Python 2.7.2和PyScriptor来创建一个脚本,我希望用它来首先找到一个类型为(.shp)的文件,然后检查是否有匹配的文件具有相同的名称,但是一个(.prj)后缀。我陷入了第一部分。我希望与其他人共享此脚本,所以我试图使起始文件夹/目录成为变量。到目前为止,这是我的脚本:

# Import the operating and system modules.
import os, sys

def Main():
     # Retrieve the starting folder location.
     InFolder = sys.argv[1]
     #InFolder = "C:\\_LOCALdata\\junk"
     os.chdir(InFolder)
     print os.path.exists(Infolder)
     print InFolder

     # Begin reading the files and folders within the starting directory.
     for root, dirs, files in os.walk(InFolder):
         print os.path.exists(root)
         for file in files:
             print file
             if file.endswith(".py"):
                 print os.path.join(root, file)
             elif file.endswith(".xlsx"):
                 print os.path.join(root, file)
             elif file.endswith(".shp"):
                 print "Shapefile present."
             elif file.endswith(".txt"):
                 print "Text file present."
             else:
                 print "No Python, Excel or Text files present."
     return()

print "End of Script."
sys.exit(0)


if __name__ == '__main__':
    sys.argv = [sys.argv[0], r"C:\_LOCALdata\junk"]
    Main()

到目前为止,我得到的唯一结果是:

*** Remote Interpreter Reinitialized  ***
>>> 
End of Script.
Exit code:  0
>>> 

有什么建议吗?

莱恩

2 个答案:

答案 0 :(得分:0)

你甚至有机会开始之前就退出了你的剧本!删除或缩进这些行:

print "End of Script."
sys.exit(0)

从顶部开始程序化(就像python一样),我们:

  1. 导入库
  2. 定义Main功能。
  3. 打印一行,然后立即退出!
  4. 您的__name__ == '__main__'永远不会到达。

答案 1 :(得分:0)

哦,男人 - 呃。感谢您的投入。我确实得到了它的工作。代码搜索shapefile(.shp),然后查找匹配的投影文件(.prj)并打印没有投影文件的shapefile。这是完成的代码:

# Import the operating and system modules.
import os, sys

def Main():
    # Retrieve the starting folder location.
    InFolder = sys.argv[1]

    text = (InFolder + "\\" + "NonProjected.txt")
    outFile = open(text, "w")
    # Begin reading the files and folders within the starting directory.
    for root, dirs, files in os.walk(InFolder):
        for file in files:
            if file.endswith(".shp"):
                PRN = os.path.join(root,(str.rstrip(file,"shp") + "prj"))
                if os.path.exists(PRN):
                    pass
                else:
                    outFile.write((str(os.path.join(root,file))) + "\n")
                    print os.path.join(root,file)
            else:
                pass

    outFile.close()
    print
    print "End of Script."
    sys.exit(0)

    return()

 #================================================================================
 if __name__ == '__main__':
     sys.argv = [sys.argv[0], r"G:\GVI2Hydro"]
     #sys.argv = [sys.argv[0], r"C:\_LOCALdata"]
     #sys.argv = [sys.argv[0], r"U:"]
     Main()