重点参考 博客1和 博客2
python 读取
'''
文件的保存格式如下:
ct0000.ply\t\t-0.36530579898806004\t\t0.9083753114754733\t\t0.2034845613984805\t\t-0.22148492260620195\t\t0.12749980261766858\t\t-0.9667927541053358\t\t-0.9041549105567143\t\t-0.3982437618272161\t\t0.15461501829346225
'''
name=[]
Rot_Mat=[]
with open(os.path.join(file_path, 'list.txt'),'r') as file_to_read:
while True:
lines=file_to_read.readline()
if not lines:
break
pass # pass 一般用于占位置,因为有时如果定义一个空函数程序会报错,当你没有想好函数的内容是可以用 pass 填充,使程序可以正常运行
ss=lines.split('\t\t') # 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,'字符。这里是'\t\t',所以这样写
name=np.append(name,ss[0])
rot_mat=np.zeros([3,3],np.float)
for i in range(3):
for j in range(3):
rot_mat[i,j]=np.float(ss[i*3+j+1])
Rot_Mat.append(rot_mat)
c++ 读取
文件的输入输出
1.fstream提供了三个类,用来实现c++对文件的操作。(文件的创建、读、写)。
ifstream :从已有的文件读入
ofstream : 向文件写内容
fstream : 打开文件供读写
2.文件打开模式:
ios::in 只读
ios::out 只写
ios::app 从文件末尾开始写,防止丢失文件中原来就有的内容
ios::binary 二进制模式
ios::nocreate 打开一个文件时,如果文件不存在,不创建文件
ios::noreplace 打开一个文件时,如果文件不存在,创建该文件
ios::trunc 打开一个文件,然后清空内容
ios::ate 打开一个文件时,将位置移动到文件尾
3.文件指针位置的用法
ios::beg 文件头
ios::end 文件尾
ios::cur 当前位置
例子:
file.seekg(0,ios::beg); //让文件指针定位到文件开头
file.seekg(0,ios::end); //让文件指针定位到文件末尾
file.seekg(10,ios::cur); //让文件指针从当前位置向文件末方向移动10个字节
file.seekg(-10,ios::cur); //让文件指针从当前位置向文件开始方向移动10个字节
file.seekg(10,ios::beg); //让文件指针定位到离文件开头10个字节的位置
注意:移动的单位是字节,而不是行。
getline 函数操作
参考博文
读取str 和 int 数组
对于 .txt 文件的格式如下图(每行为:xxx.ply\t\tnum0\t\t…\t\tnum8):
读取的代码如下:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string file_name = "E:\\xia\\University\\graduate\\work\\3D\\3D_registration\\our_project\\ma_project\\PointNet\\Dataset\\Test\\Normalization\\list.txt";
ifstream infile(file_name);
if (!infile.is_open()){
cout << "can't open the file!" << endl;
return 0;
}
string s; //用于读取 每行前面的字符串
double a[3][3]; //用于读取每行后面的数字
int i = 0;
while ((i<100) && getline(infile, s, '\t')){ //要读取的流是infile,将流中的字符读到s中,遇到'\t'便停止读取
infile >> a[0][0] >> a[0][1] >> a[0][2] >> a[1][0] >> a[1][1] >> a[1][2] >> a[2][0] >> a[2][1] >> a[2][2];
/*cout << s << '\t' << a[0][0] << '\t' << a[0][1] << '\t' << a[0][2] << '\t' << a[1][0] << '\t' << a[1][1]
<< '\t' << a[1][2] << '\t' << a[2][0] << '\t' << a[2][1] << '\t' << a[2][2];*/
cout << s << endl;
getline(infile, s);//去掉 末尾的'\n'
i++;
}
return 0;
}