Python 输入多行,读取txt文件

1. 使用input

input a: 23
23 <class 'str'>

2.使用sys.stdim.readine()

    import sys
    c = sys.stdin.readline() #单行文本,回车结束
    #sys.stdin.readline().strip('\n') 去掉换行符
    print(c, type(c))

23234353454
23234353454 <class ‘str’>

3. 输入多行文本,用while循环

    while True:
        try:
            bottles.append(int(input()))
        except:
            #当输入非int型时,如小数,空格等,抛出异常
            for i in bottles:
                print(i)
            break

2
5
5.6
2
5
Process finished with exit code 0

4. 从txt中读取文件

import numpy as np

def read_txt(file):
    with open(file, 'r') as f:
        data = f.readlines()    #读取文本所有内容,并且以数列的格式返回结果,一般配合for in使用

        # 创建一个list存起来
        ls=[]
        for line in data:
			# 截掉换行符
            line=line.strip('\n')
            # print(line)
            # 以空格进行分割
            ll=line.split(' ')
            # print(ll,type(ll[0]),type(ll[1]),type(ll[2]))
            ls.append(ll)
        lsn=np.array(ls)
        print(len(ls),lsn.shape,ls)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值