Read方法的使用
- 使用open方法打开文件
- 使用read可以读文件内容,是所有的内容一次性输出
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print(f.read())

- 读取文件的部分内容,使用参数n返回部分内容
- 如果n=6,读取文件内容的前面6个字符
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print(f.read(6))

Read 配合seek使用
- seek是指定其指针的位置
- 使用n=* 的数量,用来返回从第seek位置指定开始,返回n个字符的字符串,类似字符串的截取操作
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print('-'*20)
f.seek(2) #从第2个字符开始
print(f.read(4)) #往后4个字符串输出

Readline方法的使用
- 与read方法类似,可以添加参数n
- Readline是读取的是一行,如果多次调用,就会每行输出,从第一行开始输出
- 读取多行内容需要多次调用readline
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print('-'*20)
print(f.readline())
print(f.readline())

Readline方法的使用,使用参数N限制输出字符串
- N 小于整行的字符串数字,显示出N的字符串
- N 大于整行的字符串数字,显示出整行内容
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print(f.readline(3))

f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print(f.readline(30))

Readlines方法的使用
- 反正所有内容,是以列表的形式返回
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print(f.readlines())

- N如果小于字符串长度,返回第一行
- N如果大于字符串长度,返回从第二行的字符串数量总和
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print(f.readlines(3))

f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print(f.readlines(30))

加油 2020-3-8
网友评论