读写txt文件

时间:2013-06-20 08:04:29

标签: matlab

我有一个exif文件,我想在csv文件中读取和写入数据。

这只是一个示例文件,真实的文件太复杂而且很长。

---- File ----
File Name                       : IMG_5547.JPG
Directory                       : .
File Size                       : 3.1 MB
File Modification Date/Time     : 2013:05:27 18:10:31+02:00
File Access Date/Time           : 2013:06:19 13:53:37+02:00
File Creation Date/Time         : 2013:06:19 13:53:37+02:00
File Permissions                : rw-rw-rw-
File Type                       : JPEG
MIME Type                       : image/jpeg
Exif Byte Order                 : Little-endian (Intel, II)
Image Width                     : 4000
Image Height                    : 3000
Encoding Process                : Baseline DCT, Huffman coding
Bits Per Sample                 : 8
Color Components                : 3
Y Cb Cr Sub Sampling            : YCbCr4:2:2 (2 1
......
.......
.......

'muster.txt'

File Name                       : IMG_5547.JPG
GPS Time Stamp                  : 08:52:21
GPS Latitude                    : 52.419358°
GPS Longitude                   : 9.652666°
GPS Altitude                    : 140.1 m

%阅读文件

fid = fopen('muster.txt','r');

filename_ = fgetl(fid);
Skip2_ = fgetl(fid);   // **HOW CAN I SKIP MORE THAN ONE LINE ?????**
GPS_Latitude =fgetl(fid);
GPS_Longitude =fgetl(fid);
GPS_Altitude =fgetl(fid);
fclose(fid);

%转入csv文件

%OUtput应该是这样的

%sample_out.csv

IMG_5547  52.419358  9.652666  140.1

我想知道如何从('filename_,'GPS Latitude','GPS_Longitude','GPS_Altitude')获取所需的值并写入csv文件

1 个答案:

答案 0 :(得分:1)

以下是我将如何解决此问题:

% read in the file and convert to array of characters
fid = fopen('muster.txt');
A = char(fread(fid))';
fclose(A);
% create a cell array of strings for each line in the file
fileLines = regexp(A,'\n','split');
% use the ' : ' as a kind of delimiter between the field name
% and the data
toks = regexp(fileLines,'\s+:\s+','split');
% create a structure to hold the data, and fill it
data = struct();
for ii=1:length(toks)
  currTok = toks{ii};
  data.(char(regexprep(currTok{1},'\s+',''))) = char(regexprep(currTok{2},'\s+',''));
end
% write the csv file
fid = fopen('sample_out.csv','w');
fprintf(fid,'%s %s %s %s %s\n,...data.FileName, ...
                                 data.GPSTimeStamp, ...
                                 data.GPSLatitude, ...
                                 data.GPSLongitude,data.GPSAltitude);
fclose(fid);

当然,有更有效的方法,但鉴于问题陈述,我会从这里开始。

HTH!