matlab - Having trouble conditionally moving files based on their names
问题描述
I am trying to write a script that will auto sort files based on the 7th and 8th digit in their name. I get the following error: "Argument must be a string scalar or character vector"
. Error is coming from line 16:
Argument must be a string scalar or character vector.
Error in sort_files (line 16) movefile (filelist(i), DirOut)
Here's the code:
DirIn = 'C:\Folder\Experiment' %set incoming directory
DirOut = 'C:\Folder\Experiment\1'
eval(['filelist=dir(''' DirIn '/*.wav'')']) %get file list
for i = 1:length(filelist);
Filename = filelist(i).name
name = strsplit(Filename, '_');
newStr = extractBetween(name,7,8);
if strcmp(newStr,'01')
movefile (filelist(i), DirOut)
end
end
Also, I am trying to make the file folder conditional so that if the 10-11 digits are 02 the file goes to DirOut/02 etc.
解决方案
First, try avoid using the eval
function, it is pretty much dreaded as slow and hard to understand. Specially if you need to create variables. Instead do this:
filelist = dir(fullfile(DirIn,'*.wav'));
Second, the passage:
name = strsplit(Filename, '_');
Makes name
a list, so you can access name{1}
or possibly name{2}
. Each of these are strings. But name
isn't a string, it is a list. extractBetween
requires a string as an input. That is why you are getting this problem. But note that you could have simply done:
newStr = name(7:8);
If name was a string, which in Matlab is a char
array.
EDIT:
Since it has been now claimed that the error occurs on movefile (filelist(i), DirOut)
, the likely cause is because filelist(i)
is a struct. Wheres a filena name (char array) should have been given at input. The solution should be replacing this line with:
movefile(fullfile(filelist(i).folder, filelist(i).name), DirOut)
Now, if you want to number the output folders too, you can do this: movefile(fullfile(filelist(i).folder, filelist(i).name), [DirOut,filesep,name(7:8)])
This will move a file to /DirOut/01. If you wanted /DirOut/1, you could do this:
movefile(fullfile(filelist(i).folder, filelist(i).name), [DirOut,filesep,int2str(str2num(name(7:8)))])
推荐阅读
- powershell - 使用批处理脚本在不断变化的文件中查找字符串
- javascript - 如何使用 axios 从服务器获取有限的数据?
- c++ - 什么时候调用 constinit 对象的析构函数?
- r - R中的线性搜索
- python - int 未被正确识别为 csv 中的 int
- amazon-web-services - 我应该设置什么最低权限才能授予 S3 文件上传访问权限?
- node.js - Bigquery如何在List操作期间过滤表和视图
- angular - Observable 稍后返回数据
- sql-server - 从一个响应为任何的表中选择所有记录,并从另一个响应为无的表中选择记录
- docker - 无法使用 docker 的 IP 地址访问 Web 应用程序,但 localhost 很好