将txt文件中的数据导入到数组中最Python的方式是什么? [重复]

问题描述 投票:0回答:1

我在 MATLAB 中有这段代码

txtFiles = dir('*.txt') ; %loads txt files
N = length(txtFiles) ; 

for i = 1:N
    data = importdata(txtFiles(i).name);
    x = data(:,1);
    y(:,i) = data(:,2) ;
end

它获取我所有 100 个 txt 文件并为 x 创建一个数组,然后将 y 数据存储在一个单独的数组中,其中每一列对应于不同的 txt 文件的值。

Python中有类似的技巧吗?

这就是数据文件的构建方式:

896.5000000000 0.8694710776
896.7500000000 0.7608314184
897.0000000000 0.6349069122
897.2500000000 0.5092121001
897.5000000000 0.3955858698
python arrays concatenation txt
1个回答
1
投票

你可以用多种方式表达:

使用单衬管

import glob
# This can be further shortened, but will result in a less clear code.
# One quality of a pythonic code

# Gets file names and reads them.
data = [open(file).read() for file in glob.glob('*.txt')]

# each block of data has it's line split and is put
# into seperate arrays

# [['data1 - line1', 'data1 - line2'], ['data2 - line1',...]]
data = [block.splitlines() for block in data]

x = [] # for column-1
y = [] # for column-2

# takes each line within each file data
# splits it, and appends to x and y

data = [
        # this splits by the spaces
        # example line: -2000        data1
        # output  = ['-2000', 'data']

        x.append(line.split()[0]) or y.append(line.split()[1])
        # splits it, and appends to x and y
        for file_data in data for line in file_data
        # takes each line within each file data
        ]

无单衬

import glob

x, y = [], []
# x : column 1
# y : column 2

# For each text file in dir
for file in glob.glob('*.txt'):

    # open the file
    with open(file) as _:

        # read and splitlines
        for line in _.read().splitlines():

            # split the columns
            line = line.split()

            # this splits by the spaces
            # example line: -2000        data1
            # output  = ['-2000', 'data']

            # append to lists
            x.append(line[0])
            y.append(line[1])

结果:

print (x) # ['896.5000000000', '896.7500000000', '897.0000000000', '897.2500000000', '897.5000000000']
print (y) # ['0.8694710776', '0.7608314184', '0.6349069122', '0.5092121001', '0.3955858698']
© www.soinside.com 2019 - 2024. All rights reserved.