首页 > 编程语言 >python读文件

python读文件

时间:2023-02-02 14:04:18浏览次数:33  
标签:count 文件 python readlines read print open

第一种方法

#encoding=utf-8
file = open("./man_data.txt","r")
try:
print file.read()
finally:
file.close()

第二种方法

#encoding=utf-8
try:
with open('./man_data.txt','r') as man_file:
data=man_file.read()
print data
except IOError as err:
print('file error:'+str(err))

 第三种方法,逐行读取

#encoding=utf-8
fr = open("/myspace/mywork/python/sh_id.txt")
while True:
line = fr.readline().strip()
if len(line) == 0:
break
print line
fr.close()

 另外的一些注意:

#encoding=utf-8  

print '中国'

#计算一个文件中有多少行

#文件比较小
count = len(open(r"d:\123.txt",'rU').readlines())
print count

#文件比较大
count = -1

for count,line in enumerate(open(r"d:\123.txt",'rU')):
pass
count += 1

print count

#更好的方法
count = 0

thefile = open(r"d:\123.txt",'rb')

while True:
buffer = thefile.read(1024 * 8192)
if not buffer:
break
count += buffer.count('\n')
thefile.close()

print count

文件对象提供了三个“读”方法: .read()、.readline() 和 .readlines()。每种方法可以接受一个变量以限制每次读取的数据量,但它们通常不使用变量。 .read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。

然而 .read() 生成文件内容最直接的字符串表示,但对于连续的面向行的处理,它却是不必要的,并且如果文件大于可用内存,则不可能实现这种处理。

.readline() 和 .readlines() 非常相似。它们都在类似于以下的结构中使用:

fh = open('c:\\autoexec.bat')
  for line in fh.readlines():
  print line

.readline() 和 .readlines() 之间的差异是后者一次读取整个文件,

像 .read() 一样。

.readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理。

另一方面,.readline() 每次只读取一行,通常比 .readlines() 慢得多。

仅当没有足够内存可以一次读取整个文件时,才应该使用 .readline()。



标签:count,文件,python,readlines,read,print,open
From: https://blog.51cto.com/u_2820398/6033530

相关文章