Python 读取.txt, .md等文本文件

# example.md
1 2 3
4 5 6
7 8 9

>>> with open('example.md') as f:
        lines = f.readlines()
>>> lines
['1 2 3\n', '4 5 6\n', '7 8 9\n']
# 我们发现每一行后面都会有一个回车符,我们使用strip()函数消除它
>>> lines = [i.strip() for i in lines]
['1 2 3', '4 5 6', '7 8 9']
# 每个元素是一个string,但是我们需要读取的是文本数据,所以需要将string转化为int(or float)
>>> data = []
>>> for line in lines:
        data.append([int(i) for i in line.split(' ')])
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 最后可以把list转化为ndarray形式
>>> data = np.array(data)
>>> data
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
# 把上述步骤写到一个函数里
>>> def read_file(file):
        """
        read .md or .txt format file
        :param file: .md or .txt format file
        :return: data
        """
        with open('example.md') as f:
            lines = f.readlines()
        data = []
        for line in lines:
            data.append([int(i) for i in line.strip().split(' ')])
        return np.array(data)
>>> data = read_file('example.md')
>>> data
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

 

你可能感兴趣的:(python,python,读取文件)