Python读取文件的方法

3,715次阅读
没有评论

共计 914 个字符,预计需要花费 3 分钟才能阅读完成。

一般说来,每当你需要重复一个运算或者重复处理某件事的时候,循环就很方便。因为文件包含了许多字符和行,他们也是循环常见的典型使用案例之一,要把
文件内容一次加载至字符串,可以调用read:

file = open('test.txt','r')
               print(file.read())

但是,要分块加载文件,通常要么是编写一个while循环,在文件结尾时使用break,要么写个for循环。要按照字符读取时,下面的两种代码编写方式都可以。

file = open('test.txt')
               while True:
                   char = file.read(1)   #read by character
                   if not char:break
                   print(char)
        
               for char in open('test.txt').read():
                   print(char)

这里的for也会处理每个字符,但是会一次把文件加载至内存,要以while循环按行或按块读取时,可以使用类似于下面的代码:

file = open('test.txt')
               while True:
                   line = file.readline()   #read by line
                   if not line:break
                   print(line,end='')                   

               file = open('test.txt','rb')
               while True:
                   line = file.read(10)   #read byte chunks:up to 10 bytes
                   if not chunk:break
                   print(chunk)

通常是按照块读入二进制数据的。不过,逐行读取文本文件时,for循环是最易于编写以及执行最快的选择。

for line in open('test.txt').readlines():
                   print(line,end='')

               for line in open('test.txt'):          #Use iterators:best text input mode
                   print(line,end='')

文件readlines方法会一次把文件载入到行字符串的列表,这里最后的例子则按照文件迭代器来自动在每次循环迭代的时候读入一行。
这里的最后一个例子通常是文本文件的最佳选择,它除了简单,还对任意大小的文件爱你都有效、并且不会一次把整个文件都载入到内存中。

正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2017-03-01发表,共计914字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码