IDL学习笔记-创建与读取文件
;创建与读取文件,以txt格式为例
;Caption:如何把数据写入文件?
IDL> file=‘F:\CRFurtherStudy\IDL\IDL85Workspace\source code\HelloWorld\cr1.txt’
;此时目录下还没有file文件,只是定义了一个file的字符串变量
IDL> openw,lun,file,/get_lun
;此时可以在目录下找到定义的txt空文件
IDL> arr=indgen(5,4)
IDL> printf,lun,arr
;利用printf向刚刚创建的txt文件写入一个数组arr,但此时打开txt文件还看不见arr的数组,需要释放lun(free_lun)
IDL> free_lun,lun
;此时可以在目录中看到写有arr数组的txt文件
EXAMPLE:
IDL> file=‘F:\CRFurtherStudy\IDL\IDL85Workspace\source code\HelloWorld\cr1.txt’
IDL> arr=indgen(5,4)
IDL> printf,lun,arr
IDL> free_lun,lun
;如何在已经写入数据的文件中继续写入数据?
IDL> openw,lun,file,/get_lun,/append
;在openw命令中添加关键字/append(appendix的缩写)
IDL> printf,lun,‘cr’
;接着利用printf继续写入想输入的数据
IDL> free_lun,lun
;不要忘记free_lun之后才能在txt文件中查看到输入的数据
EXAMPLE:
IDL> openw,lun,file,/get_lun,/append
IDL> printf,lun,‘cr’
IDL> free_lun,lun
;如果输入的数据太长,txt文件中一行显示不出来强制换行怎么办?
IDL> arr=indgen(13,5)
IDL> openw,lun,file,/get_lun
IDL> printf,lun,arr
IDL> free_lun,lun
;此时cr1文件中数组情况如图:
;此时文本中一行显示不了138这么多字符,因此需要加入width关键字控制输出的格式如下:(注意这里要解释一下为什么是138,因为数组是13列,每一个数据为int,占8个位置,因为width要设置至少为138)
IDL> openw,lun,file,/get_lun,width=138
IDL> printf,lun,arr
IDL> free_lun,lun
;输出结果为13*5的数组如图:
如何读取文件中的数据?
;将刚刚输入文本的135数组读取到我们需要的data变量中
IDL> openr,lun,file,/get_lun
;openr命令,意思是打开读取名字叫lun的file文件
IDL> data=intarr(135)
;定义一个13*5的0数组data用于等会儿储存数据
IDL> readf,lun,data
;利用readf命令将lun中的数据读取到data变量中储存
EXAMPLE:
IDL> openr,lun,file,/get_lun
IDL> data=intarr(13*5)
IDL> readf,lun,data
紧接着:如何继续读取下面的数据?
IDL> tmp=’’
;首先定义个string变量tmp用于储存接下来读取的数据
IDL> openr,lun,file,/get_lun
;常规的openr命令(openread)
IDL> skip_lun,lun,5,/lines
;跳过5行读取下面的数据
IDL> readf,lun,tmp
IDL> tmp
cr
EXAMPLE:
IDL> tmp=’’
IDL> openr,lun,file,/get_lun
IDL> skip_lun,lun,5,/lines
IDL> readf,lun,tmp
IDL> tmp
cr
如果事先不知道cr1.txt文件中的数组是几行几列,但他们格式很整齐,比如都是int整型,那么如何读取?
思路是先计算出文件中的数据是几行几列的,然后readf
IDL> IDL> openr,lun,file,/get_lun
IDL> nl=file_lines(file)
;读取文件的行数nl
IDL> t=’ ’
IDL> readf,lun,t
;将文件的第一行数据写入t,这里由于t是string,因此恰好是读取第一行(如果是数组就是读取几行几列)
IDL> crsplit=strsplit(t,’ ')
;利用strsplit函数将t用空格‘ ’拆分,存入变量crsplit
IDL> nr=n_elements(crsplit)
;crsplit中元素的个数即为文件中数据的列数
IDL> data1=intarr(nr,nl)
IDL> openr,lun,file,/get_lun
IDL> readf,lun,data1
;将文件中数据存入data1
EXAMPLE:
IDL> IDL> openr,lun,file,/get_lun
IDL> nl=file_lines(file)
IDL> t=’’
IDL> readf,lun,t
IDL> crsplit=strsplit(t,’ ')
IDL> nr=n_elements(crsplit)
IDL> data1=intarr(nr,nl)
IDL> openr,lun,file,/get_lun
IDL> readf,lun,data1