文本文件:readfile.txt
详细描述:
read() #一次性读取文本中全部的内容,以字符串的形式返回结果
readline() #只读取文本第一行的内容,以字符串的形式返回结果
readlines() #读取文本所有内容,并且以列表的格式返回结果,一般配合for in使用
具体案例1:readlines()一次读取文本的所有内容,并且以列表的格式返回结果数据
import pymongo #激活MongoDb数据库 client = pymongo.MongoClient(‘localhost‘,27017) #数据库名称、类似于一张excel表 walden = client[‘walden‘] #excel文件下创建一个表单 sheet_tab = walden[‘sheet_tab‘] path = ‘D:/Spider/readfile.txt‘ with open(path,‘r‘) as f: line1 = f.readlines() print(line1)
运行结果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Spider/channel_lists.py [‘昌林\n‘, ‘旺旺\n‘, ‘寒岳\n‘, ‘若尘‘] Process finished with exit code 0
具体案例2:readline()只读取文本第一行的内容,以字符串的形式返回结果
import pymongo #激活MongoDb数据库 client = pymongo.MongoClient(‘localhost‘,27017) #数据库名称、类似于一张excel表 walden = client[‘walden‘] #excel文件下创建一个表单 sheet_tab = walden[‘sheet_tab‘] path = ‘D:/Spider/readfile.txt‘ with open(path,‘r‘) as f: line1 = f.readline() print(line1)
运行结果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Spider/channel_lists.py 昌林 Process finished with exit code 0
具体案例3:read()一次性读取文本中全部的内容,以字符串的形式返回结果
import pymongo #激活MongoDb数据库 client = pymongo.MongoClient(‘localhost‘,27017) #数据库名称、类似于一张excel表 walden = client[‘walden‘] #excel文件下创建一个表单 sheet_tab = walden[‘sheet_tab‘] path = ‘D:/Spider/readfile.txt‘ with open(path,‘r‘) as f: line1 = f.read() print(line1)
运行结果:
C:\Users\licl11092\AppData\Local\Programs\Python\Python35\python.exe D:/Spider/channel_lists.py 昌林 旺旺 寒岳 若尘 Process finished with exit code 0
引用故事:
>>> f.read() #调用read()函数
‘Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday\n‘ #返回结果
>>> f.readline() #调用readline()函数
‘Monday\n‘ #返回结果
>>> f.readlines() #调用readlines()函数
[‘Tuesday\n‘, ‘Wednesday\n‘, ‘Thursday\n‘, ‘Friday\n‘, ‘Saturday\n‘, ‘Sunday\n‘] #返回结果
时间: 2024-10-12 22:28:29