文本文件的读写 template, C++ , Python版本

首先是C++的版本,完成对txt文件的读写操作

* 读文件三大类 : (1)ofstream : 写文件 (2)ifstream : 读文件 (3)fsream : 读写文件

1 文本文件

  1. 1 写文件
    步骤:
    (1)包含头文件 #include < fstream > (2)创建流对象 ofstream ofs
    (3)打开文件 ofs.open (“文件路径” ,打开方式) (4)写数据 ofs <<“写入数据”
    (5)关闭文件 ofs.close()

在这里插入图片描述

文件的写操作,可以说是比较无脑了,判断是否打开成功,然后一股脑的把数据扔进去就可以了
std::ofstream save_parameter;
save_parameter.open("parameter.txt", std::ios::out);
if(!save_parameter.is_open()){
    std::cout<<"open the parameter.txt failed..."<<std::endl;
}
else{
    save_parameter<<_polyCoeff;
    save_parameter.close();
}

std::ofstream save_timer;
save_timer.open("save_timer.txt", std::ios::out);
if(!save_timer.is_open()){
    std::cout<<"open the save_timer.txt failed..."<<std::endl;
}
else{
    save_timer<<_polyTime;
    save_timer.close();
}
文件的读操作
  1. 2 读文件与写文件步骤类似,但读取方式比较多。
    步骤:
    (1)包含头文件 #include < fstream > (2)创建流对象 ifstream ifs
    (3)打开文件并判断文件是否打开成功 ifs.open (“文件路径” ,打开方式) (4)读数据 四种方式读取
    (5)关闭文件 ifs.close()
首先定义两个Eigen数组
Eigen::Matrix<double,MINISNAP_ROW,MINISNAP_COL>parameter;
Eigen::Matrix<float,MINISNAP_ROW,1>poly_timer;
通过如下通用代码完成对应文件的读操作以及赋值操作
std::fstream infile;
  infile.open("/home/chasing/Downloads/mavros_controller/parameter.txt",std::ios::in);
  if(!infile.is_open()){
      ROS_ERROR("error for load the parameters.txt....");
      exit(EXIT_FAILURE);
  }else{
        for(uint8_t i=0;i<MINISNAP_ROW;i++){
            for(uint8_t j=0;j<MINISNAP_COL;j++){
                infile >> parameter(i,j);
            }
        }
  }
  infile.close();
  
  for(uint8_t i=0;i<MINISNAP_ROW;i++){
      for(uint8_t j=0;j<MINISNAP_COL;j++){
            std::cout<< parameter(i,j)<<"\t";
      }
      std::cout<<std::endl;
  }
  
  std::fstream timefiles;
  timefiles.open("/home/chasing/Downloads/mavros_controller/save_timer.txt",std::ios::in);
  if(!timefiles.is_open()){
      ROS_ERROR("error for load the timer.txt...");
      exit(EXIT_FAILURE);
  }else{
    for(uint8_t i=0;i<MINISNAP_ROW;i++){
      timefiles >> poly_timer(i);
    }
    ROS_INFO("reading the timer data successfully...");
  }
  timefiles.close();

然后是python的版本,完成对txt文件的读写操作

data = open("logfile.txt","r")
print(data.read()) 
print(data.readline())
print(data.readlines())

其中 r 表示以读的方式打开文件,对应的是"a+"表示是以追加写的形式打开。
read()函数表示一次性全部读取过来,返回的数据类型是字符串。
readline()表示只读取一行数据。 readlines()表示读取多行数据,返回的是一个元祖
然后是对应的数据的写操作。测试代码如下:

a = 20
b = np.random.random((2,3))
data = open("logfile.txt","a+")
print("This is a test, a= %.3f" %a, file=data)
print(b,file=data)
data.close()

Remark: 文件的读和写要分开打开完成操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值