Python:从文件中读取各种数据类型

时间:2015-04-12 14:31:08

标签: python matlab numpy scipy

我从matlab切换到python。 我要导入的数据就像这样

4
6
2
1
2.0E8
0.2
0.002

1 2 6
2 3 4
2 4 5
2 5 6

0 0
1 0
2 0
2 1
1 1
0 1

4 0 -150

1 1 1
6 1 1

这就是我在matlab

中阅读的内容
FP1=fopen('471220580.txt','rt');
NELEM=fscanf(FP1,'%d',1);
NPION=fscanf(FP1,'%d',1);
NVFIX=fscanf(FP1,'%d',1);
NFORCE=fscanf(FP1,'%d',1);
YOUNG=fscanf(FP1,'%e',1);
POISS=fscanf(FP1,'%f',1);
THICK =fscanf(FP1,'%f',1);
LNODS=fscanf(FP1,'%d',[3, NELEM])';  
COORD=fscanf(FP1,'%f',[2,NPION])';  
FORCE=fscanf(FP1,'%f',[3,NFORCE])';  
FIXED=fscanf(FP1,'%d',[3,NVFIX])';  

如何在python中导入这些数据?我在fscanf中找不到python的等效内容。

What is the equivalent of Matlab 'fscanf' in Python? numpy.loadtxt需要Each row in the text file must have the same number of values。这不适合我的情况。

2 个答案:

答案 0 :(得分:0)

循环遍历文件中的行,如

for line in open("file.txt"):
     parse(line)

parse方法是一种将行作为输入并输出整数,浮点数或整数列表的方法。

对于整数 - > var = int(line)

浮动 - > var = float(line)

有关整数列表 - > var = map(int, line.split())

对于矩阵 - >考虑一下你想要一个m X n矩阵。 所以请阅读m行,从上面的循环中读取 -

matrix = []

count = m
for line in open():
    if count > 0:
        matrix.append(map(int, line.split()))

答案 1 :(得分:0)

with open('471220580.txt') as text_file:
    all_numbers = text_file.read().split("\n")
    all_numbers = filter(None, all_numbers)
    #the all_numbers list contains all the distinct values from the file
    #Now to initialize various variables you can use following methods:

    #Method1:
    NELEM = all_numbers[0]
    NPION = all_numbers[1]
    #and so on ... 

    #Note: Keep in mind that the values stored in these variables is of type str


   #Method2:
   NELEM, NIPON ,... = all_numbers

使用Method1优于Method2的优势在于您可以在method1中使用类型转换,您可以使用var1 = type(var)

来实现此目的
NELEM = int(all_numbers[0])
NPION = int(all_numbers[1])
POISS = float(all_numbers[5])

对于构成矩阵的第9-12行,我们可以将矩阵表示为列表列表。

matrix_row1 = map(int, all_numbers[9])    #[1, 2, 3]
matrix_row2 = map(int, all_numbers[10])   #[4, 5, 6]
matrix_row3 = map(int, all_numbers[11])   #[7, 8, 9]

matrix = [matrix_row1, matrix_row2, matrix_row3]
#[[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]]