一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Python 文本文件的内容读入操作

时间:2011-05-07 编辑:简简单单 来源:一聚教程网

python 将文本文件的内容读入可以操作的字符串变量非常容易。文件对象提供了三个“读”方法: .read()、.readline() 和 .readlines()。每种方法可以接受一个变量以限制每次读取的数据量,但它们通常不使用变量。 .read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。然而 .read() 生成文件内容最直接的字符串表示,但对于连续的面向行的处理,它却是不必要的,并且如果文件大于可用内存,则不可能实现这种处理

打开文件

print "opening and closing the file."
text_file = open("read_it.txt", "r")
text_file.close()

读取一行

print "nreading one line at a time."
text_file = open("read_it.txt", "r")
print text_file.readline()
print text_file.readline()
print text_file.readline()
text_file.close()

读取一个字符

print "nreading characters from a line."
text_file = open("read_it.txt", "r")
print text_file.readline(1)
print text_file.readline(5)
text_file.close()

读取整个文件输出

print "nreading the entire file into a list."
text_file = open("read_it.txt", "r")
lines = text_file.readlines()
print lines
print len(lines)
for line in lines:
    print line
text_file.close()

一行行读取文件

print "nlooping through the file, line by line."
text_file = open("read_it.txt", "r")
for line in text_file:
    print line
text_file.close()

简介一下上面用到open函数

f=open('/tmp/hello','w')

#open(路径+文件名,读写模式)

#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式

 

热门栏目