# Source code for datExtract

    """
    This script should be executed from the directory that contains .dat files generated by Abaqus CAE during analysis.
    It can be used to extract the critical buckling load values from each analysis ``.dat`` file and then store them within a
    single ``.dat`` file.
    """

    def eigenvals(path):
        """
        This function extracts all the eigenvalues from the list of .dat
        files and saves them into a single .dat file

        :param path: path to the .dat files generated by Abaqus CAE

        :type path: str

        :return: list of eigenvalues

        :rtype: list
        """

        walk_dir = os.path.abspath(path)  # Convert to absolute path
        print('Root directory is %s' % walk_dir)
        content = []
        # Extract content of each .dat file
        files = next(os.walk(walk_dir))[2]
        files.sort()
        for filename in [f for f in files if f.endswith(".dat")]:
            with open(os.path.join(walk_dir, filename), 'r') as f:
                content.append(f.read().splitlines())
        # Extract eigenvalues
        eig_list = []
        for item in content:
            for index, line in enumerate(item):
                if ' MODE NO      EIGENVALUE' in line:
                    # Extracting eig by its position
                    eig_list.append(item[index + 3:index + 11])
        # Transforming to float:
        eig_float = [[float(j.split()[1]) for j in x] for x in eig_list]
        # Write into a .csv file
        with open("eig_list_new.dat", "w") as f:
            writer = csv.writer(f)
            writer.writerows(eig_float)
        return eig_float

    if __name__ == '__main__':
        import os
        import csv
        # Exporting mesh statistics:
        path = './'
        eigfloat = eigenvals(path)