Python 讀取.txt, .md等文字檔案
阿新 • • 發佈:2019-01-01
# 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]])