How to open files based on information from another file?

조회 수: 3 (최근 30일)
pink flower
pink flower 2020년 9월 20일
댓글: Ameer Hamza 2020년 9월 20일
I have a .txt file with 7 columns and thousands of rows, as follows:
20140101 2240 140213 -5.543 -34.973 32.4 2000
20140101 2250 118094 -4.475 -35.372 28.2 2000
20140101 1930 196279 -6.136 -33.958 24.2 3000
20140101 0000 178273 -6.082 -34.284 25.8 4000
20140101 1600 238772 -6.073 -33.188 28.4 6000
20140102 2340 86399 -7.214 -35.951 26.0 15000
I need to open the other files according to the strings in column 1, 2 and 7. That is, the files would have the following structure:
precip_CZ_$column7_$column1_$column2.dat
For example, this is the file name:
precip_CZ_02000_20140101_2240.dat
precip_CZ_02000_20140101_2250.dat
precip_CZ_03000_20140101_1930.dat
precip_CZ_04000_20140101_0000.dat
precip_CZ_06000_20140101_1600.dat
precip_CZ_15000_20140102_2340.dat
  댓글 수: 2
stozaki
stozaki 2020년 9월 20일
Hello pink flower,
Does the "precip_CZ_02000_20140101_2240.dat" file contain 140213 -5.543 -34.973 32.4 as data?
stozaki

댓글을 달려면 로그인하십시오.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 9월 20일
Try this
f = fopen('data.txt');
data = textscan(f, '%f %f %f %f %f %f %f');
fclose(f);
data = [data{:}];
filenames = compose('precip_CZ_%05d_%08d_%04d.dat', data(:,7), data(:,1), data(:,2))
output
>> filenames
filenames =
6×1 cell array
{'precip_CZ_02000_20140101_2240.dat'}
{'precip_CZ_02000_20140101_2250.dat'}
{'precip_CZ_03000_20140101_1930.dat'}
{'precip_CZ_04000_20140101_0000.dat'}
{'precip_CZ_06000_20140101_1600.dat'}
{'precip_CZ_15000_20140102_2340.dat'}
Read these .dat files using load(), readmatrix() or other similar functions.
  댓글 수: 2
pink flower
pink flower 2020년 9월 20일
This worked for me. Thanks! How can I use fopen?
Ameer Hamza
Ameer Hamza 2020년 9월 20일
fopen() itself is not important. The correct method depends on how the data is present in your .dat file.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2020년 9월 20일
data = load('YourFile.txt');
filenames = "precip_CZ_" + data(:,7) + "_" + data(:,1) + "_" + data(:,2) + ".dat";
nfiles = numel(filenames);
for K = 1 : nfiles
thisfile = filenames(K);
[fid, msg] = fopen(thisfile);
if fid < 0
fprintf('Error opening file "%s" because "%s"\n', thisfile, msg);
continue
end
do something
fclose(fid)
end

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by