1.read([size])
方法用于从文件读取指定的字节数,如果未给定或为负则读取所有。
语法
read() 方法语法如下:
fileObject.read();
参数
-
size -- 从文件中读取的字节数。
返回值
返回从字符串中读取的字节。
test.txt文件中内容:
(1)read([size])
方法从文件当前位置起读取size个字节
注意:size ,包括换行符
代码:
A=open('test.txt')
print 'Aname:'+A.name
size=A.read(8)
print 'size:'+size
print (type(size))
A.close()
输出结果:
Aname:test.txt
size:a1
bb2
c
<type 'str'>
(2)read()若无参数size,则表示读取至文件结束为止,它返回为字符串对象。
代码:
A = open('test.txt')
read =A.read()
print 'read():' +read
print (type(read))
输出:
read():a1
bb2
cc3
<type 'str'>
(3)从文件当前位置起读取
第一次read(8)读取到c字母,再接着读,就输出c2
代码:
A=open('test.txt')
print 'Aname:'+A.name
size=A.read(8)
print 'size:'+size
print (type(size))
# A.close()
read =A.read()
print 'read():' +read
print (type(read))
输出:
Aname:test.txt
size:a1
bb2
c
<type 'str'>
read():c3
<type 'str'>