Python цикл по файлам - PullRequest
       3

Python цикл по файлам

0 голосов
/ 13 сентября 2018

У меня есть код Python, который вставлен ниже. Это прекрасно работает для того, что мне нужно сделать. Вы можете заметить, что я загружаю в один файл дампа. Как я могу перебрать все файлы дампа, которые имеют одинаковый конечный шаблон * .dump, и чтобы каждый новый файл просто добавлял новый столбец данных в выходной файл? По сути, я хочу добавить цикл, поэтому мне не нужно вручную переписывать код для каждого файла дампа.

from ovito.io import *
from ovito.data import *
from ovito.modifiers import *
import numpy as np

node = import_file("../200eV.dump",multiple_frames = True)

# Perform Wigner-Seitz analysis:
ws = WignerSeitzAnalysisModifier(
    per_type_occupancies = True, 
    eliminate_cell_deformation = True)
ws.reference.load("../../../WS_Ref/ws.dump")
node.modifiers.append(ws)

# Define a modifier function that selects sites of type A=1 which
# are occupied by exactly one atom of type B=2.
def modify(frame, input, output):

    # Retrieve the two-dimensional Numpy array with the site occupancy numbers.
    occupancies = input.particle_properties['Occupancy'].array

    # Get the site types as additional input:
    site_type = input.particle_properties.particle_type.array

    # Calculate total occupancy of every site:
    total_occupancy = np.sum(occupancies, axis=1)

    # Set up a particle selection by creating the Selection property:

    selection1 = (site_type == 1) & (occupancies[:,0] == 0) & (occupancies[:,1] == 0)

    output.attributes['Ca_Vac'] = np.count_nonzero(selection1)


# Insert Python modifier into the data pipeline.
node.modifiers.append(PythonScriptModifier(function = modify))

# Let OVITO do the computation and export the number of identified 
# antisites as a function of simulation time to a text file:
export_file(node, "defects_200.txt", "txt", 
    columns = ['Timestep', 'Ca_Vac'],
    multiple_frames = True)

Ответы [ 2 ]

0 голосов
/ 13 сентября 2018
import numpy as np
from ovito.data import *
from ovito.io import *
from ovito.modifiers import *

ws = WignerSeitzAnalysisModifier(
    per_type_occupancies=True,
    eliminate_cell_deformation=True)
ws.reference.load("../../../WS_Ref/ws.dump")


def modify(frame, input, output):
    occupancies = input.particle_properties['Occupancy'].array

    site_type = input.particle_properties.particle_type.array

    total_occupancy = np.sum(occupancies, axis=1)  # you are also not using, also not using the frame parameter

    selection1 = (site_type == 1) & (occupancies[:, 0] == 0) & (occupancies[:, 1] == 0)

    output.attributes['Ca_Vac'] = np.count_nonzero(selection1)


import glob

for file in glob.glob('../*.glob'):
    node = import_file(file, multiple_frames=True)
    node.modifiers.append(ws)
    node.modifiers.append(PythonScriptModifier(function=modify))
    export_file(
        node, "defects_200.txt", "txt",
        columns=['Timestep', 'Ca_Vac'],
        multiple_frames=True
    )

Не зная больше, это лучшее, что я могу придумать, надеюсь, это сработает!

Добавление этой части согласно запросу ОП.

for index, file in enumerate(glob.glob('../*.glob')):
    node = import_file(file, multiple_frames=True)
    node.modifiers.append(ws)
    node.modifiers.append(PythonScriptModifier(function=modify))
    export_file(
        node, "defects_{}.txt".format(index), "txt",
        columns=['Timestep', 'Ca_Vac'],
        multiple_frames=True
    )

И снова, это предположение о том, как библиотека работает и будет работать, только если исходный код выдаст defetcs_200.txt в результате.

0 голосов
/ 13 сентября 2018

Попробуйте пакет python glob.

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...