循环通过txt中保存的路径列表

时间:2014-10-22 08:44:04

标签: python

我有下面的代码可以处理,它需要在'myfolder'中设置的路径并且拉上与shp相关联的所有文件类型(我没有写它,其他一些聪明的火花确实)。但是我想要聪明并遍历包含许多路径列表的文本文件。我必须掌握循环遍历txt文件并打印出文件路径列表的概念,但我不确定如何将这两者联系起来。任何帮助都会很棒。

的Si

简单循环

items = 'shp_folders.txt'

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

创建zip文件的代码。

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."  

3 个答案:

答案 0 :(得分:1)

阿。我看到Tubeliar已回应你的评论,但我会在这里留下这个答案,因为它有更多细节。

要修复NameError: name 'zipShapefile' is not defined,您需要将zipShape文件导入到循环遍历'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中找到的所有路径中压缩形状文件,然后继续尝试在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."

答案 1 :(得分:0)

应该像

一样简单
items = 'shp_folders.txt'

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

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

答案 2 :(得分: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()