Home > Mobile >  How to use the for loop and formatting for reading txt files?
How to use the for loop and formatting for reading txt files?

Time:08-03

Could someone help me to transform this matlab code into a python code?

y = 1995:2022;
for yr = y
    Data_A = importdata(sprintf('Data_%d_A.txt', yr));
    Data_B = importdata(sprintf('Data_%d_B.txt', yr));
    Data_C = importdata(sprintf('Data_%d_C.txt', yr));
    result = inv(eye(size(data_A)) - data_A)   data_B*data_C;
    xlswrite('result_file.xlsx',result,string(sprintf('%d', yr)), 'C3');
end

It is actually a code that reads files of type A, B and C and from 1995 to 2022 (data_1995_A, Data_1996_A, Data_1997_A, data_1995_B, Data_1996_B, Data_1997_B, data_1995_C, Data_1996_C, Data_1997_C...), make simple calculation and write the results in excel where each sheet represents a year.

I could write it in MATLAB as seen above, but I struggle to write it in python. Could someone help please?

CodePudding user response:

To read file and write them into variables;

A_files_list =[]

for i in (1995,2003):
    f = open(f'Data_{i}_A.txt')
    text = f.read()
    A_files_list.append(text)
    f.close()

But instead of this approach, I would advice using pandas library to read txt files and saving them as DataFrames, then you can calculate and merge them as another DataFrame and save as later. Below sharing another post that you can use for that purpose;

Load data from txt with pandas

CodePudding user response:

You need to use the range() function as

for x in range(1995,2022):

and x is your variable that, in this case, counts from 1995 to 2021

Some documentation about for loops and range() function

Anyway, if you want to elaborate large file pandas is the solution

  • Related