python从txt文件中读取数字,并放入list中

如题所述

第1个回答  2017-08-11
# nums.txt
12312
123

3233
4
4
4


556

# read_nums.py
# -*- coding: UTF-8 -*-

__author__ = 'lpe234'

FILE_PATH = './nums.txt'


def read_file(file_path):
    tmp_list = list()
    with open(file_path, 'r') as f:
        txt = f.read()
        for line in txt.split('\n'):
            if line.isdigit():
                tmp_list.extend(line.split())
    return tmp_list


print read_file(FILE_PATH)

# result
python read_nums.py
['12312', '123', '3233', '4', '4', '4', '556']

Process finished with exit code 0

本回答被网友采纳
相似回答