读取文件

python读取一列数据

data.txt

AAAAF110 0003E818 0003E1FC 0003E770 0003FFFC 90
AAAAF110 0003E824 0003E208 0003E76C 0003FFFC A5
AAAAF110 0003E814 0003E204 0003E760 0003FFFC 85
AAAAF110 0003E7F0 0003E208 0003E764 0003FFFC 68
AAAAF110 0003E7CC 0003E1FC 0003E758 0003FFFC 2B

pytest.py

# encoding: utf-8
import codecs
 
f = codecs.open('data.txt', mode='r', encoding='utf-8') # 打开txt文件,以‘utf-8'编码读取
line = f.readline()  # 以行的形式进行读取文件
list1 = []
while line:
  a = line.split()
  b = a[2:3]  # 这是选取需要读取的位数
  list1.append(b) # 将其添加在列表之中
  line = f.readline()
f.close()
 
for i in list1:
  print(i)
python pytest.py
[u'0003E1FC']
[u'0003E208']
[u'0003E204']
[u'0003E208']
[u'0003E1FC']

C++读取一列数据

data.txt

AAAAF110 0003E818 0003E1FC 0003E770 0003FFFC 90
AAAAF110 0003E824 0003E208 0003E76C 0003FFFC A5
AAAAF110 0003E814 0003E204 0003E760 0003FFFC 85
AAAAF110 0003E7F0 0003E208 0003E764 0003FFFC 68
AAAAF110 0003E7CC 0003E1FC 0003E758 0003FFFC 2B

main.cpp

#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>
 
using namespace std;
 
int main(){
 
	ifstream myfile("G:\\博客\\C++\\C++读取文本中的一列\\test.txt");
 
	if (!myfile.is_open()){
		cout << "Unable to open myfile";
		system("pause");
		exit(1);
 
	}
 
	vector<string> vec;
	string temp;
 
 
	while (getline(myfile, temp))                    //利用getline()读取每一行,并按照行为单位放入到vector
	{
		vec.push_back(temp);
	}
 
	vector <float> radius;
 
 
	cout << "读入的数据为 " << endl;
	for (auto it = vec.begin(); it != vec.end(); it++)
	{
		cout << *it << endl;
		istringstream is(*it);                    //用每一行的数据初始化一个字符串输入流;
		string s;
		int pam = 0;
		
		while (is >> s)                          //以空格为界,把istringstream中数据取出放入到依次s中
		{
			if (pam == 5)                       //获取第六列的数据
 
			{
				float r = atof(s.c_str());     //做数据类型转换,将string类型转换成float
				radius.push_back(r);
				//cout << r << endl;
			}
 
			pam++;
 
		}
	}
	cout << "读入的第6列数据为 " << endl;
 
	for (auto it = radius.begin(); it != radius.end(); it++)
	{
		cout << *it << endl;
	}

	return 1;
}
g++ main.cpp
./a.out
读入的数据为
AAAAF110 0003E818 0003E1FC 0003E770 0003FFFC 90
AAAAF110 0003E824 0003E208 0003E76C 0003FFFC A5
AAAAF110 0003E814 0003E204 0003E760 0003FFFC 85
AAAAF110 0003E7F0 0003E208 0003E764 0003FFFC 68
AAAAF110 0003E7CC 0003E1FC 0003E758 0003FFFC 2B
读入的第6列数据为
90
0
85
68
2
posted @ 2020-05-11 23:13  多弗朗强哥  阅读(106)  评论(0编辑  收藏  举报