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)