I need to extract the first value of the following code:
3.43099,70.8539,91.701,FAIL
The file has the '.sol' extension, but it can be read in notepad or Matlab.
I just want to know how to to read in all *.sol files in a folder and how to write the extracted value in a text file.
Thanks a lot, i would be grateful.
NEW
ita='"';
for i=1:size(z,2)
word_to_replace=input('Replace? ','s');
tik=input('Replacement? ','s');
coluna=input('Column? ');
files = dir('*.txt');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
fh = fopen(files(i).name,'w');
val=num2str(z(i,coluna));
word_replacement=strcat(tik,val,ita);
contents = regexprep(contents,'word_to_replace','word_replacement');
fprintf(fh,contents); % write "replaced" string to file
fclose(fh) % close out file
end
end
end
Many thanks
File extension does not make a difference as to what MATLAB can "read", use the fileread command to load in the file and parse its contents. You can then split on commas, since it looks like it is comma separated
files = dir('*.sol');
fh = fopen('outFile.txt','w');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
parts = regexp(contents,',','Split');
fprintf(fh,[parts{1},'\n']);
end
end
fclose(fh)
This should do what you want. It will find all files in the current directory with the .sol extension, loop through all of them, grab the first value, and write it out to a text file.
Find and replace
Finding and replacing is relatively simple as well. You can do the same looping, read the file contents, run a replacement, and then rewrite that out to the same file.
files = dir('*.sol');
for i = 1:numel(files)
if ~files(i).isdir % make sure it is not a directory
contents = fileread(files(i).name);
fh = fopen(files(i).name,'w'); % open handle to same file just read for overwriting
contents = regexprep(contents,'toReplace','replacement'); % do string replacement
fprintf(fh,contents); % write "replaced" string to file
fclose(fh) % close out file
end
end
Related
I have a folder with 10 subfolder each has about 100 different files including text files and different extension images. I just need to copy the image files with JPG extension and move it to another single folder.
I am using this code:
clear all
clc
M_dir = 'X:\Datasets to be splitted\Action3\Action3\'% source directory
D_dir = 'X:\Datasets to be splitted\Action3\Depth\'
files = dir(M_dir);% main directory
dirFlags = [files.isdir];
subFolders = files(dirFlags);%list of folders
for k = 1 :length(subFolders)
if any(isletter(subFolders(k).name))
c_dtry = strcat(M_dir,subFolders(k).name)
fileList = getAllFiles(c_dtry)%list of files in subfolder
for n1 = 1:length(fileList)
[pathstr,name,ext] = fileparts(fileList{n1})% file type
%s = dir(fileList{n1});
%S = s.bytes/1000;%file size
Im = imread(fileList{n1});
%[h,w,d] = size(Im);%height width and dimension
if strcmp(ext,'.jpg')|strcmp(ext,'.JPG')%)&S>=50&(write image dimension condition))% here you need to modify
baseFileName = strcat(name,ext);
fullFileName = fullfile(D_dir, baseFileName); % No need to worry about slashes now!
imwrite(Im, fullFileName);
else
end
end
end
end
But the code is stopped with an error when a text file being processed.
The error says:
Error using imread>get_format_info (line 491)
Unable to determine the file format.
Error in imread (line 354)
fmt_s = get_format_info(fullname);
Error in ReadFromSubFolder (line 16)
Im = imread(fileList{n1});
Thanks
Your code is reading the data before you check the extension
Im = imread(fileList{n1});
is before
if strcmp(ext,'.jpg')|strcmp(ext,'.JPG')
edit
For finding files which end 'vis' you can usestrcmp
strcmp ( name(end-2:end), 'vis' )
For completeness you should also check that name is longer than 3 char.
Here is a relatively simpler solution using dir and movefile or copyfile depending on whether you want to move or copy:
%searching jpg files in all subdirectories of 'X:\Datasets to be splitted\Action3\Action3'
file = dir('X:\Datasets to be splitted\Action3\Action3\**\*.jpg');
filenames_with_path = strcat({file.folder},'\',{file.name});
destination_dir = 'X:\Datasets to be splitted\Action3\Depth\';
%mkdir(destination_dir); %create the directory if it doesn't exist
for k=1:length(filenames_with_path)
movefile(filenames_with_path{k}, destination_dir, 'f'); %moving the files
%or if you want to copy then: copyfile(filenames_with_path{k}, destination_dir, 'f');
end
I want to read the data of a file with size about 60 MB into matlab in some variables, but I get errors. This is my code:
clear all ;
clc ;
% Reading Input File
Dataz = importdata('leak0.lis');
%Dataz = load('leak0.lis');
for k = 1:1370
foundPosition = 1 ;
for i=1:size(Dataz,1)
strp = sprintf('I%dz=',k);
fprintf(strp);
findValue = strfind(Dataz{i}, strp) ;
if ~isempty(findValue)
eval_param = strp + '(foundPosition) = sscanf(Dataz{i},''%*c%*c%*f%*c%*c%f'') ;';
disp(eval_param);
% str(foundPosition) = sscanf(Dataz{i},'%*c%*c%*f%*c%*c%f') ;
eval(eval_param);
foundPosition = foundPosition + 1 ;
end
end
end
When I debugged it, I found out that the dataz is empty & so it doesn't proceed to next lines. I replace it with fopen, load & etc, but it didn't work.
From the Matlab help files, import data is likely failing because it doesn't understand your file format.
From the help files
Name and extension of the file to import, specified as a string. If importdata recognizes the file extension, it calls the MATLAB helper function designed to import the associated file format (such as load for MAT-files or xlsread for spreadsheets). Otherwise, importdata interprets the file as a delimited ASCII file.
For ASCII files and spreadsheets, importdata expects to find numeric
data in a rectangular form (that is, like a matrix). Text headers can
appear above or to the left of the numeric data, as follows:
Assuming that your .lis files actually have delimited text.
You should adjust the delimiter in the importdata call so that Matlab can understand your file.
filename = 'myfile01.txt';
delimiterIn = ' ';
headerlinesIn = 1;
A = importdata(filename,delimiterIn,headerlinesIn);
I need to check whether a wav file in Matlab work folder exists ou not. If it does, I need to load the file into a variable (file in my case), i use this code but it doesn't work.
if strcmp(file,'\n')==0
file='test.wav';
elseif findstr(file,'.')==''
file=strcat(file,'.wav');
end
[TestWave,Fs] = audioread(file);
You don't say if you are trying to find a particular .WAV file, or just any .WAV file...
If you just want to know if a particular file (of any kind) exists, use the exist() function. It returns value 2 if a file exits:
myFileName = 'test.wav';
myDirectory = 'c:\temp';
filepath = fullfile(myFileName,myDirectory);
if exist(filepath,'file') == 2
[TestWave,Fs] = audioread(file);
end
Otherwise, just search for the files you need using dir():
myDirectory = 'c:\temp';
wildcard = '*.wav';
theseFiles = dir(fullfile(myDirectory,wildcard));
for i = 1:length(theseFiles)
thisFilePath = fullfile(myDirectory,theseFiles(i).name);
[TestWave,Fs] = audioread(thisFilePath); % Load this file
% Do something with the loaded file...
end
I am new to matlab and image analysis. I would really appreciate some insight/help into the following problem. I am trying to rename images (jpg) in a folder that have a random name into specific (new) names. I made the an excel file with two columns the first column contains the old names and the second column the new names. I found the next code on stack overflow (Rename image file name in matlab):
dirData = dir('*.jpg'); %# Get the selected file data
fileNames = {dirData.name}; %# Create a cell array of file names
for iFile = 1:numel(fileNames) %# Loop over the file names
newName = sprintf('image%05d.jpg',iFile); %# Make the new name
movefile(fileNames{iFile},newName); %# Rename the file
end
The code gives all the photos a new name based on the old one but that is not what I want, the new names I use are not linked to the old ones. I tried the following code :
g= xlsread('names.xlsx') % names.xlsx the excel file with old and new names
for i=1:nrows(g)
image=open(g(i,1));
save(g(i,2),image);
end
It doesn't work. I get the error message :using open (line 68)
NAME must contain a single string. I don't think open is the right function to use.
Thank you !
How about this:
% Get the jpeg names
dir_data = dir('*.jpg');
jpg_names = {dir_data.name};
% Rename the files according to the .xlsx file
[~,g,~] = xlsread('names.xlsx'); % Thanks to the post of Sean
old_names = g(:,1);
new_names = g(:,2);
for k = 1:numel(old_names)
% check if the file exists
ix_file = strcmpi(old_names{k}, jpg_names);
if any(ix_file)
movefile(old_names{k}, new_names{k});
end;
end;
It seems like g = xlsread(file) reads only numeric data from file (see here). The third output argument of xlsread returns raw data including strings; does the following work? (i don't have excel and can't test it)
[~, ~, g] = xlsread('names.xlsx')
for i = 1:nrows(g)
movefile(g{i,1}, g{i,2})
end
What is the best way to figure out the size of a file using MATLAB? The first thought that comes to mind is size(fread(fid)).
Please see the dir function as stated above.
Please note that the dir function works on files and not on directories only.
>> s = dir('c:\try.c')
s =
name: 'try.c'
date: '01-Feb-2008 10:45:43'
bytes: 20
isdir: 0
datenum: 7.3344e+005
You can use the DIR function to get directory information, which includes the sizes of the files in that directory. For example:
dirInfo = dir(dirName); %# Where dirName is the directory name where the
%# file is located
index = strcmp({dirInfo.name},fileName); %# Where fileName is the name of
%# the file.
fileSize = dirInfo(index).bytes; %# The size of the file, in bytes
Or, since you are looking for only one file, you can do what Elazar said and just pass an absolute or relative path to your file to DIR:
fileInfo = dir('I:\kpe\matlab\temp.m');
fileSize = fileInfo.bytes;
Use the fact that MatLab has access to Java Objects:
myFile = java.io.File('filename_here')
flen = length(myFile)
If you don't want to hardcode in your directory, you can use the built in pwd tool to find the current directory and then add your file name to it. See example below:
FileInfo = dir([pwd,'\tempfile.dat'])
FileSize = FileInfo.bytes
The question seems to indicate that fopen/fread/.. is used. In this case, why not seeking to the end of the file and reading the position?
Example:
function file_length = get_file_length(fid)
% extracts file length in bytes from a file opened by fopen
% fid is file handle returned from fopen
% store current seek
current_seek = ftell(fid);
% move to end
fseek(fid, 0, 1);
% read end position
file_length = ftell(fid);
% move to previous position
fseek(fid, current_seek, -1);
end
Matlab could have provided a shortcut..
More on ftell can be found here.
This code works for any file and directory (no need for absolute path) :
dirInfo=dir(pwd);
index = strcmp({dirInfo.name},[filename, '.ext']); % change the ext to proper extension
fileSize = dirInfo(index).bytes
Easy way to find size of file is:
enter these cammands
K=imfinfo('filename.formate');
size_of_file=K.FileSize
and get size of file.