2014-10-22 4 views
0

У меня есть следующий бит кода, который работает с обработкой, он принимает путь, установленный в «myfolder», и застегивает все типы файлов, связанные с shp (я не писал его, какая-то другая умная искра). Однако я хочу быть умным и перебирать текстовый файл, содержащий список множества путей. Я должен понять концепцию цикла через txt-файл и распечатать список путей к файлу, но я не уверен, как бы я связал их. Любая помощь будет большой.Проход по списку путей, пройденный в txt

Si

Simple Loop

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, но затем он идет, чтобы попытаться и почтовые папки в пути форме 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 содержит функцию для zip содержимого папки, как определено как myFolder. То, что я хочу сделать, это заставить zipshapes.py прокручивать каждый из путей в txt-файле и застегивать содержимое этой папки. – geomiles

+0

Хорошо. Я добавлю больше информации к моему ответу. Дайте мне минутку ... –

+0

Приветствия за это, я вижу, как ваш цикл теперь. полный ответ ниже. – geomiles

0

Это должно быть так же просто, как

items = 'shp_folders.txt' 

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

импорта также файл, содержащий определение функции zipShapefile. Поместите оператор импорта сверху и оставьте расширение .py.

+0

Приветствия за это, и я вижу, что вы делаете, но получаете сообщение об ошибке: NameError: name 'zipShapefile' не определен. – geomiles

+0

Импортируйте другой файл. Я отредактировал ответ. – Tubeliar

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()' есть небольшая проблема; Я поставлю улучшенную версию в свой ответ. –

Смежные вопросы