2016-06-14 3 views
1

Привет всем, я начинаю с python, и у меня есть проблема с моим кодом. Я бы хотел импортировать и прочитать весь файл .BVH из определенной папки, но программа занимает только первое один из папки. Вот мой код. Я использую blender для визуализации.импортировать и читать все файлы из папки Python

import bpy # This module gives access to blender data, classes, and functions 
import os # This module provides a unified interface to a number of operating system functions. 
import sys # This module provides a number of functions and variables that can be used to manipulate different parts of the Python runtime environment. 

path = "C:\\Users\\PC\\Desktop\\Rotate Prototype\\filtered" 
dir = os.listdir("C:\\Users\\PC\\Desktop\\Rotate Prototype\\filtered") 

files = 0 
for files in dir: 
    if files.lower().endswith('.bvh'): 
     try: 

      bpy.ops.object.delete() # Deletes the cube 

      bpy.ops.import_anim.bvh(filepath="C:\\Users\\PC\\Desktop\\Rotate Prototype\\filtered\\pick_001_3_fil_Take_001.bvh", axis_forward='-Z', axis_up='Y', filter_glob="*.bvh", target='ARMATURE', global_scale=1.0, frame_start=1, use_fps_scale=False, update_scene_fps=False, update_scene_duration=False, use_cyclic=False, rotate_mode='NATIVE') # We import a bvh file with the appropriate settings 

      bpy.context.scene.render.fps = 72 # We configure the frame rate 

      bpy.ops.export_anim.bvh(filepath="C:\\Users\\PC\\Desktop\\Rotate Prototype\\trolled\\haha.bvh", check_existing=True, filter_glob="*.bvh", global_scale=1.0, frame_start=1, frame_end=1515, rotate_mode='XYZ', root_transform_only=True) # We export the file with the appropriate settings 

     except: 
       print ("Couldn't open file")     
files++ 
+0

Я не думаю, что файлы ++ действительны для кода python. – mattsap

+0

Каков ваш вопрос? Если у вас возникла ошибка, покажите свой результат с ошибкой. – mattsap

+0

Что означает 'files ++'? Если он подсчитывает импортированные файлы, он должен быть отступом в предложении try. В любом случае, python не разрешает '' '' '' '' '' '' '' '' '' '' '' '' '' '' + + = 1' –

ответ

2

Вы не используете фактический файл в цикле for. Каждый раз вы используете один и тот же жесткий путь.

Возможно, вы хотите что-то вроде ниже?

Я переименовал files в file_path, чтобы лучше представить, что находится в этой переменной. Затем я использовал это значение в вызове import_anim.bvh, а затем снова использовал его в вызове export_anim.bvh. (Там я прикрепил на "_exported.bvh" в конце имени файла. Я не был уверен, что вы пытаетесь сделать.)

for file_path in dir: 
    if file_path.lower().endswith('.bvh'): 
     try: 
      bpy.ops.object.delete() # Deletes the cube 

      # We import a bvh file with the appropriate settings 
      bpy.ops.import_anim.bvh(filepath=file_path, 
       axis_forward='-Z', axis_up='Y', filter_glob="*.bvh", 
       target='ARMATURE', global_scale=1.0, frame_start=1, 
       use_fps_scale=False, update_scene_fps=False, 
       update_scene_duration=False, use_cyclic=False, 
       rotate_mode='NATIVE') 

      bpy.context.scene.render.fps = 72 # We configure the frame rate 

      # We export the file with the appropriate settings 
      bpy.ops.export_anim.bvh(
       filepath=file_path + '_exported.bvh', 
       check_existing=True, filter_glob="*.bvh", 
       global_scale=1.0, frame_start=1, frame_end=1515, 
       rotate_mode='XYZ', root_transform_only=True) 

     except: 
      print ("Couldn't open file")     
+0

Большое спасибо .. я получаю это !!! –

+2

Исключения, такие как FileNotFoundError, должны рассматриваться как таковые. Избегайте попыток уловов, в которых вы не обрабатываете ошибку но просто ловите что-нибудь. –

1

Вы используете files как для подсчета и проведения текущего пути к файлу в каждом итерация. И в итерации вы не вводите текущий путь к файлу до , вы просто использовали путь жесткого кодированного файла. Кроме того, ++ не является допустимым синтаксисом.

files = 0 
for file_path in dir: 
    if file_path.lower().endswith('.bvh'): 
     try: 
      bpy.ops.object.delete() # Deletes the cube 
      bpy.ops.import_anim.bvh(filepath=file_path, axis_forward='-Z', axis_up='Y', filter_glob="*.bvh", target='ARMATURE', global_scale=1.0, frame_start=1, use_fps_scale=False, update_scene_fps=False, update_scene_duration=False, use_cyclic=False, rotate_mode='NATIVE') # We import a bvh file with the appropriate settings 
      bpy.context.scene.render.fps = 72 # We configure the frame rate 
      bpy.ops.export_anim.bvh(filepath=file_path, check_existing=True, filter_glob="*.bvh", global_scale=1.0, frame_start=1, frame_end=1515, rotate_mode='XYZ', root_transform_only=True) # We export the file with the appropriate settings 
      files += 1 
     except: 
      print ("Couldn't open file: {}".format(file_path)) 
+0

Вы уверены, что используете функции bvh? Отлаживаете свой код, печатаете, вы друг. –

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