我有下面的代码作品一个款待,它需要在'我的文件夹'中设置的路径,并拉上与一个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."
感谢PM 2ring为您的答案,但我仍然有点困惑。也许我没有很好地解释自己。我的shp_folder.txt包含路径名称列表,zipshapes.py包含压缩文件夹内容的函数,定义为myFolder。我期望做的是让zipshapes.py循环访问txt文件中的每个路径并压缩该文件夹的内容。 – geomiles 2014-10-22 10:00:34
好的。我会在我的答案中添加更多信息。给我一分钟... – 2014-10-22 10:08:23
为此欢呼,我看你现在循环如何。完整答案如下。 – geomiles 2014-10-22 10:26:29