python读取txt⽂件没读到400⾏_python读取txt⽂件1、打开⽂件
#1)
1 f = open("","r") #设置⽂件对象
2 f.close() #关闭⽂件
3
4 #2)
5 #为了⽅便,避免忘记close掉这个⽂件对象,可以⽤下⾯这种⽅式替代
6 with open('',"r") as f: #设置⽂件对象
7 str = f.read() #可以是随便对⽂件的操作
2、读取txt⽂件
1)readline()#⼀⾏⼀⾏的读取
1 #第⼀种⽅法
2 f = open("","r") #获取⽂件对象
3 line =f.readline()
4 line = line[:-1]
5 while line: #直到读取完⽂件
6 line = f.readline() #读取⼀⾏⽂件,包括换⾏符
7 line = line[:-1] #去掉换⾏符,也可以不去
8 f.close() #关闭⽂件
2)循环读取
1 filepath =r'E:\a.txt’
2
3 f = open(filepath, "r")
4 for x inf:
5 print(x)
6 f.close()
3)readlines()#全部读取
1 f = open("","r") #设置⽂件对象
2 datalist = f.readlines() #直接将⽂件中按⾏读到list⾥,效果与⽅法2⼀样
3 f.close() #关闭⽂件
2、写⽂件
1 str=‘sssss’
2 with open('','w') as f: #设置⽂件对象
3 f.write(str) #将字符串写⼊⽂件中
——————————————— 练习—————————————————————————————————————————————
1、获取指定⾏内容
1 '''********************************************************
2 Func Name: getTextLine
3 Para: filename : ⽂件路径
4 row : ⾏
5 return: testline : 指定⾏内容
6 Desc: 读取txt⽂件指定⾏的内容
7 Date: 20190730
8 Auth: yanerfree9
********************************************************'''
python怎么读文件10 defgetTextLine(filename, n):11 f=open(filename,"r",encoding='utf_8')12 textlist = f.readlines()#将⽂件内容全部读取到textlist中,⽂件不能太⼤,类型:list
13 f.close() #关闭⽂件
14 '''
15 with open('filename',"r",encoding='utf_8') as f: #设置⽂件对象16 textlist = f.readlines()17 '''
18 rows =len(textlist)19 print('⽂件⾏数- rows=%d'%rows)20 linetext = textlist[n%rows-1]21 print('linetext=%s'%linetext)22 return linetext

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。