python txt文件读取
设置文件地址
path = 'D:/硕博/博士生期间资料/机器学习/机器学习课程资料/HW1/data/本纪list格式/高祖本纪.txt'
f.read()
with open(path,'r',encoding='utf-8') as f:
d1 = f.read() #一次性读取txt全部内容,结果是一个str
f.readlines()
with open(path,'r',encoding='utf-8') as f1:
d2 = f1.readlines() #按行读取txt内容,结果是一个list,len(list)=txt行数
print(d2)
3. f.readline()
with open(path,'r',encoding='utf-8') as f2:
d3 = f2.readline()#只读取txt一行数据,结果是一个str
print(d3)
#高祖
可以通过f.readline(size)
设置size的值,限定从一行中读取的字符串的个数
with open(path,'r',encoding='utf-8') as f3:
d4 = f3.readline(1)
d4
#Out[11]: '高'