美文网首页Python
Python基础(33) - read,readline和rea

Python基础(33) - read,readline和rea

作者: xianling_he | 来源:发表于2020-03-08 15:52 被阅读0次

Read方法的使用

  • 使用open方法打开文件
  • 使用read可以读文件内容,是所有的内容一次性输出
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print(f.read())
hexianling.png
  • 读取文件的部分内容,使用参数n返回部分内容
  • 如果n=6,读取文件内容的前面6个字符
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print(f.read(6))
hexianling.png

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个字符串输出
hexianling.png

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())
hexianling.png

Readline方法的使用,使用参数N限制输出字符串

  • N 小于整行的字符串数字,显示出N的字符串
  • N 大于整行的字符串数字,显示出整行内容
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print(f.readline(3))
hexianling.png
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\综合学习\\files\\temp.txt')
print(type(f))
print(f.readline(30))
hexianling.png

Readlines方法的使用

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

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

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

print(f.readlines(30))
hexianling.png

加油 2020-3-8

相关文章

网友评论

    本文标题:Python基础(33) - read,readline和rea

    本文链接:https://www.haomeiwen.com/subject/ctnddhtx.html