Hi everyone,

I have been working with Matlab but now I have to develop a couple of programs in Python. So I am new to Python.

Could anyone tell me the python equivalent of eval command of Matlab.

Actually I have to open a set of say 100 files to read the data from them and write the extracted data to the corresponding number of files. So for example if my file name is heat1.dat, heat2.dat and so on upto heat100.dat then I use eval command to open each file and read the data as below:
str=;
eval(str);
The input arguments for this function are:

path='c:\Temp\'
fname='heat'
x =1:100

so a for loop would do it all.

Same is the case for opening a file to write

Can anyone please tell me how to do it in Python. How to open files using a loop for writing and reading.

Thanks,

mafarooqi

I think the function you may be looking for in Python is eval . Or perhaps exec , or its variant execfile , which eliminate reading the files all together.

Refer here to information on these built-in functions.

As far as how to open files within a for loop it could be something like this (untested):

file_base = 'heat'
file_ext = '.dat'
for file_num in xrange(1,101):
    file_name = file_base + str(file_num) + file_ext
    fh = open( file_name )
    file_data = fh.readlines() # or just read()
    fh.close()
    # Do something with the file data

Dear jlm699

Thanks for your help. This code works nice. For some other things I might bother you again!
Thanks,
Cheers,

mafarooqi

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.