相同点:均可接纳一个变量用以限定每一次读取的信息量 ,但一般 不应用

区别:

read() 【即 fileObject().read( [size] ) 】

特性:读取全部文件,将文件內容放到一个字符串数组变量中 。

缺点:假如文件十分大,特别是在超过运行内存时 ,没法应用read()方式。

with open(r'../learn_file/file_to_read.txt', encoding='utf-8', mode='r') as fb: content = fb.read() print(type(content)) print(content) # 輸出: # # line 1: Hello, Mike. # line 2: Nice to meet you. I'm Nick. # line 3: Welcome to Shenzhen. # line 4: Thx, it is really a beautiful city. I enjoy my time here. # line 5: It is. Shall we go for some coffee this afternoon. # line 6:Sure. And I want to discuss some details about the project we're going to work for

readline() 【即 fileObject.readline( [size] ),[size]表明可选主要参数。】

特性:从文件中一行一行地整行读取数据信息,假如特定了一个非负数的主要参数 ,则回到特定尺寸的字节 。

缺陷:比readlines()慢得多

#Python学习培训交流群:778463939 with open(r'../learn_file/file_to_read.txt', encoding='UTF-8', mode='r ') as fb: while True: content = fb.readline().replace('\n', '') # content = fb.readlines() # if not content: # break if content: print(type(content), content) else: break # print(type(content)) # print(type(content), content) print(fb.name) # 輸出: # line 1: Hello, Mike. # line 2: Nice to meet you. I'm Nick. # line 3: Welcome to Shenzhen. # line 4: Thx, it is really a beautiful city. I enjoy my time here. # line 5: It is. Shall we go for some coffee this afternoon. # line 6:Sure. And I want to discuss some details about the project we're going to work for. # ../learn_file/file_to_read.txt

readlines() 【即 fileObject.readlines( [sizeint] ),[sizeint] 表明可选主要参数】

特性:从文件一次读取全部行并返回列表,若给出sizeint > 0 ,回到总数大概为sizeint字节数的行

with open(r'../learn_file/file_to_read.txt', encoding='utf-8', mode='r') as fb: content = fb.readlines() print(type(content)) for line in content: print(type(line), line.replace('\n', '')) # 輸出 # # line 1: Hello, Mike. # line 2: Nice to meet you. I'm Nick. # line 3: Welcome to Shenzhen. # line 4: Thx, it is really a beautiful city. I enjoy my time here. # line 5: It is. Shall we go for some coffee this afternoon. # line 6:Sure. And I want to discuss some details about the project we're going to work for. 文章来源于网络 ,如有侵权请联系站长QQ61910465删除
本文版权归趣快排www.sEoguruBlog.com 所有,如有转发请注明来出,竞价开户托管,seo优化请联系QQ✈61910465