4

I have 1000 text files that their names are A0000.txt, A0001.text, ..., A1000.text. I want to read in the information in the text files and store some of them in an excel file or a csv file (csv is preferred).

How should I define a for loop that can do this task?

I can use this function A = textread('A0000.txt','%s') to read one text file, but I don't know how should I put it in a for loop. If the name of the files were 1.txt, 2.txt,..., 1000.txt it would be easier.

I would be thankful if you can provide any help.

2 Answers 2

5

You should use sprintf to generate the relevant strings:

for i=1:1000
    fileName = sprintf('A%04d.txt',i);
    A{i} = textread(fileName ,'%s')
end

The %04d tells sprintf that the number should have leading zeroes.

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

1 Comment

Thank you so much. It is working! There is just a typo : sprintf('A%04d.txt',i)
3

The following generates a list of txt files contained in the current directory. It then reads in all the files. This is useful if the file names are not sequential.

filelist = dir([pwd() filesep '*.txt' ]);
fileNames = {filelist.name}';
nFiles = length(fileNames);

for i= 1:nFiles 
    TF{i} = textread(fileNames{i},'%s');  
end

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.