2

I am new to python and programming. I have tried searching for this, but have not been able to find an answer.

I am looking for best way to take a data file append it to an array, and use it in multiple python modules. As a 1. semester science student, I know I will be using this many times during my education, so I would like some help, to find a better way to do this.

Here is an example from my first semester Group project. Where we were asked to simulate a speaker using python to help as with different tasks. We were given impedans reading to use in a data file. The data file has 3 collumns. Frequenzy, real impedance, imaginary impedance.

In the first file lets call it import_define.py . We have the following code, importing from the datafile called data.

infile = open('data.dat', 'r')
infile.readline()

freq_list = []
real_list = []
imag_list = []

for line in infile:
    split = line.split()
    freq_list.append(float(split[0][:-1]))
    real_list.append(float(split[1][:-1]))
    imag_list.append(float(split[2]))
infile.close()

import numpy as np

freqenzy = np.asarray(freq_list)
real_imp = np.asarray(real_list)
imag_imp = np.asarray(imag_list)

Then we have used the three arrays for different calculations within this module.

Now we want to use these arrays in a different module plot.py, where we want to plot some data from these 3 arrays, and from different data calculated in import_define.py

What we have done is to define 3 functions in import_define.py that return the arrays, like so:

def freq_func():
    return frequenzy

def real_imp_func():
    return real_imp

def imag_imp_func():
    return imag_imp

In the file plot.py, we did the following to import and use the arrays in this new module:

import import_define as imd

freq = imd.freq_func()
real = imd.real_imp_func()
imag = imd.imag_imp_func()

So what I would like to ask if there is a better or more correct way to do this, when using python.

1
  • You don't need the 3 functions you already imported the module so you can access freqenzy, real_imp and imag_imp. Commented Jan 22, 2014 at 13:05

4 Answers 4

1

The array variables are globals in import_define module, so you can use them directly:

import import_define as imd
print imd.frequenzy

I think you can use numpy.loadtxt to load the array from file quickly, without for loop.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, I did not know that the variables could be imported and used as well. I tried to use numpy.loadtxt with the data file,but it did not work because the file uses 2 different delimeters. Comma and colon. Here are a few sample lines from the data file: 'Freq [Hz] Z_in (real) Z_in (imag.) 10.00000010: 6.08147910, 2.55728010 10.19990010: 6.08487810, 2.60997610 10.39980010: 6.08835310, 2.66276710' How can I use, numpy.loadtxt with this file
0

No need to have those functions. From within the plot.py, you can access those variables with:

import import_define as id

id.freqenzy

Comments

0

You can implement the singleton pattern.

class ModuleSharedFile:

    class __SharedFile:
        def __init__(self, file_path):
            self.file_path = file_path
            self.array = self.__loadArray()
        def __str__(self):
            return repr(self) + self.val
        def __loadArray(self):
            # Do your stuff here.
            pass

    instance = None

    def __init__(self, file_path):
        if not ModuleSharedFile.instance:
            ModuleSharedFile.instance = ModuleSharedFile.__SharedFile(file_path)
        else:
            ModuleSharedFile.instance.file_path = file_path

    def __getattr__(self, name):
        return getattr(self.instance, name)

Then where ever you create an instance of ModuleSharedFile, you will be working with the same file/array.

Comments

0

The easiest solution is described in: "How do I share global variables across modules?": http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm

Because there is only one instance of each module, any changes made to the module object get reflected everywhere.

So instances of python modules are singletons.

You create empty file dummy.py, which gets initialized as a module.

# module1.py
import dummy
dummy.x = "value"  # set shared value

# module2.py
import dummy
print dummy.x      # read shared value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.