2014-10-22 89 views
0

我有下面的代码作品一个款待,它需要在'我的文件夹'中设置的路径,并拉上与一个SHP相关的所有文件类型(我没有写它,其他一些聪明的火花呢)。不过,我想要很聪明并循环遍历包含大量路径列表的文本文件。我必须熟悉循环一个txt文件并打印出文件路径列表的概念,但我不知道如何去关联这两个文件。任何帮助都会很棒。循环通过路径列表保存在文本文件

简单的循环

items = 'shp_folders.txt' 

with open (items) as f: 
     for line in f: 
      print(line) 
     f.seek(0) 
     for line in f: 
      print(line) 

代码来创建压缩文件。

import zipfile, sys, os, glob, shutil 

# Set the folder that contains the ShapeFiles 
myFolder = "C:/data/shp/recycling/" 

def zipShapefile(myFolder): 

    # Check if folder exists 
    if not (os.path.exists(myFolder)): 
     print myFolder + ' Does Not Exist!' 
     return False 

    # Get a list of shapefiles 
    ListOfShapeFiles = glob.glob(myFolder + '*.shp') 

    # Main shapefile loop 
    for sf in ListOfShapeFiles: 
     print 'Zipping ' + sf 

     # Create an output zip file name from shapefile 
     newZipFN = sf[:-3] + 'zip' 

     # Check if output zipfile exists, delete it 
     if (os.path.exists(newZipFN)): 
      print 'Deleting '+newZipFN 
      os.remove(newZipFN) 
      if (os.path.exists(newZipFN)): 
       print 'Unable to Delete' + newZipFN 
       return False 

     # Create zip file object 
     zipobj = zipfile.ZipFile(newZipFN,'w') 

     # Cycle through all associated files for shapefile adding them to zip file 
     for infile in glob.glob(sf.lower().replace(".shp",".*")): 
      print 'zipping ' + infile + ' into ' + newZipFN 
      if infile.lower() != newZipFN.lower() : 
       # Avoid zipping the zip file! 
       zipobj.write(infile,os.path.basename(infile),zipfile.ZIP_DEFLATED) 

     # Close zipfile 
     print 'ShapeFile zipped!' 
     zipobj.close() 

    # Got here so everything is OK 
    return True 

# Call function to zip files 
b = zipShapefile(myFolder) 

if b: 
    print "Zipping done!" 
else: 
    print "An error occurred during zipping." 

回答

1

啊。我发现Tubeliar已经回复了你的评论,但是我会留下这个答案,因为它有更多的细节。

要修复NameError: name 'zipShapefile' is not defined,您需要将zipShapefile导入通过'shp_folders.txt'循环的脚本中。

所以如果def zipShapefile(myFolder):的东西在一个名为zipshapes.py的文件中,在与循环脚本相同的文件夹中,您会将from zipshapes import zipShapefile放在循环脚本的顶部附近。

您还需要稍微修复zipshapes.py,以便在执行导入时,函数定义下的内容不会被执行。就像这样:

zipshapes.py

import zipfile, sys, os, glob, shutil 

def zipShapefile(myFolder): 
    # Check if folder exists 
    if not (os.path.exists(myFolder)): 
     print myFolder + ' Does Not Exist!' 
     return False 

    # Get a list of shapefiles 
    ListOfShapeFiles = glob.glob(myFolder + '*.shp') 

    # Main shapefile loop 
    for sf in ListOfShapeFiles: 
     print 'Zipping ' + sf 

     # Create an output zip file name from shapefile 
     newZipFN = sf[:-3] + 'zip' 

     # Check if output zipfile exists, delete it 
     if (os.path.exists(newZipFN)): 
      print 'Deleting '+newZipFN 
      os.remove(newZipFN) 
      if (os.path.exists(newZipFN)): 
       print 'Unable to Delete' + newZipFN 
       return False 

     # Create zip file object 
     zipobj = zipfile.ZipFile(newZipFN,'w') 

     # Cycle through all associated files for shapefile adding them to zip file 
     for infile in glob.glob(sf.lower().replace(".shp",".*")): 
      print 'zipping ' + infile + ' into ' + newZipFN 
      if infile.lower() != newZipFN.lower() : 
       # Avoid zipping the zip file! 
       zipobj.write(infile,os.path.basename(infile),zipfile.ZIP_DEFLATED) 

     # Close zipfile 
     print 'ShapeFile zipped!' 
     zipobj.close() 

    # Got here so everything is OK 
    return True 


def main(): 
    # Set the folder that contains the ShapeFiles 
    myFolder = "C:/data/shp/recycling/" 

    # Call function to zip files 
    b = zipShapefile(myFolder) 

    if b: 
     print "Zipping done!" 
    else: 
     print "An error occurred during zipping." 


if __name__ == '__main__': 
    main() 

有了这个修改后的版本,你现在可以安全地将其导入到其他脚本,你仍然可以运行它,就像你习惯了。

编辑

是“shp_folders.txt”有每行一个路径,每行没有多余的东西吗?如果是这样,Tubeliar的脚本需要稍作改动才能正常工作。

from zipshapes import zipShapefile 

def main(): 
    items = 'shp_folders.txt' 

    with open(items, 'r') as f: 
     for line in f: 
      zipShapefile(line.rstrip()) 


if __name__ == '__main__': 
    main() 

line.rstrip()摆脱所有的白色空间是在路径后的线,让这zipShapefile()得到的字符串是在末端不添加垃圾正确的路径。即使行末尾没有空格,也会有行尾(EOL)标记,即\n\r\r\n,具体取决于您的操作系统。


在你的答案的main()功能拉链中的所有路径的形状文件,发现在shp_folders.txt但随后继续尝试和zip文件夹形式shp_folders.txt*.shp的路径。当然,它不会找到任何东西,但它仍然有点愚蠢。:)如果zipShapefile()函数有点聪明,它会检查你传递它的路径实际上是一个目录,但目前它只是检查路径是否存在,但不关心它是目录还是纯文本文件。

无论如何,这里有一个稍微改进的main()版本,它现在报告它处理的每个路径。

def main(): 
    items = 'shp_folders.txt' 

    with open(items, 'r') as f: 
     for line in f: 
      pathname = line.rstrip() 
      print "Zipping %r" % pathname 

      # Call function to zip files in pathname 
      b = zipShapefile(pathname) 
      if b: 
       print "Zipping done!" 
      else: 
       print "An error occurred during zipping." 
+0

感谢PM 2ring为您的答案,但我仍然有点困惑。也许我没有很好地解释自己。我的shp_folder.txt包含路径名称列表,zipshapes.py包含压缩文件夹内容的函数,定义为myFolder。我期望做的是让zipshapes.py循环访问txt文件中的每个路径并压缩该文件夹的内容。 – geomiles 2014-10-22 10:00:34

+0

好的。我会在我的答案中添加更多信息。给我一分钟... – 2014-10-22 10:08:23

+0

为此欢呼,我看你现在循环如何。完整答案如下。 – geomiles 2014-10-22 10:26:29

0

它应该是越简单

items = 'shp_folders.txt' 

with open (items) as f: 
     for line in f: 
      zipShapefile(line) 

也导入包含zipShapefile函数定义的文件。将导入语句置于顶部,并省略.py扩展名。

+0

为此干杯,我看到你在做什么,但得到一个错误:NameError:name'zipShapefile'未定义。 – geomiles 2014-10-22 09:23:19

+0

导入您的其他文件。我编辑了答案。 – Tubeliar 2014-10-22 09:44:33

0

感谢Tubelair和PM 2ring在他们的帮助下提出以下答案。

import zipfile, sys, os, glob, shutil 

def zipShapefile(myFolder): 
    # Check if folder exists 
    if not (os.path.exists(myFolder)): 
     print myFolder + ' Does Not Exist!' 
     return False 

    # Get a list of shapefiles 
    ListOfShapeFiles = glob.glob(myFolder + '*.shp') 

    # Main shapefilloop 
    for sf in ListOfShapeFiles: 
     print 'Zipping ' + sf 

     # Create an output zip file name from shapefile 
     newZipFN = sf[:-3] + 'zip' 

     # Check if output zipfile exists, delete it 
     if (os.path.exists(newZipFN)): 
      print 'Deleting '+newZipFN 
      os.remove(newZipFN) 
      if (os.path.exists(newZipFN)): 
       print 'Unable to Delete' + newZipFN 
       return False 

     # Create zip file object 
     zipobj = zipfile.ZipFile(newZipFN,'w') 

     # Cycle through all associated files for shapefile adding them to zip file 
     for infile in glob.glob(sf.lower().replace(".shp",".*")): 
      print 'zipping ' + infile + ' into ' + newZipFN 
      if infile.lower() != newZipFN.lower() : 
       # Avoid zipping the zip file! 
       zipobj.write(infile,os.path.basename(infile),zipfile.ZIP_DEFLATED) 

     # Close zipfile 
     print 'ShapeFile zipped!' 
     zipobj.close() 

    # Got here so everything is OK 
    return True 


def main(): 

    items = 'shp_folders.txt' 
    myFolder = items 

    with open(items, 'r') as f: 
     for line in f: 
      zipShapefile(line.rstrip()) 


    # Call function to zip files 
    b = zipShapefile(myFolder) 

    if b: 
     print "Zipping done!" 
    else: 
     print "An error occurred during zipping." 


if __name__ == '__main__': 
    main() 
+0

当然,如果你喜欢,你可以将'zipShapefile()'定义粘贴到你的循环脚本中。但是如果你想改变'zipShapefile()'的细节,你只需要在一个地方进行更改,而不是将其粘贴到每个脚本中。但是你的'main()'有一个小问题;我会在我的答案中加入一个改进版本。 – 2014-10-22 10:40:11