python 读取txt文件

1、打开文件

#1)
1
f = open("test.txt","r") #设置文件对象 2 f.close() #关闭文件 3 4 #2) 5 #为了方便,避免忘记close掉这个文件对象,可以用下面这种方式替代 6 with open('test.txt',"r") as f: #设置文件对象 7 str = f.read() #可以是随便对文件的操作

2、读取txt文件

1)readline()#一行一行的读取

1 #第一种方法
2 f = open("test.txt","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 in f:
5     print(x)
6 f.close()

3)readlines()#全部读取

1 f = open("test.txt","r")   #设置文件对象
2 datalist = f.readlines()  #直接将文件中按行读到list里,效果与方法2一样
3 f.close()             #关闭文件

2、写文件

1 str=‘sssss’
2 with open('data.txt','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:         yanerfree
 9 ********************************************************'''    
10 def getTextLine(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
原文地址:https://www.cnblogs.com/yaner2018/p/11270697.html