Python基础——文件操作及IO流

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34120459/article/details/88038298

一、文件的基本操作:打开、读取、关闭

# 绝对路径
# f = open(r'G:\Envs\Bilitest\笔记\test.txt', 'r')
# 相对路径
f = open(r'test.txt', 'r')
print(f.read())
f.close()

1

二、文件的基本操作:写入

  • 单值写入:
f = open(r'test.txt', 'a')
f.write("我超可爱哒")
f.close()

在这里插入图片描述

  • 多值写入:
f = open(r'test.txt', 'a')
f.writelines(["我超可爱哒","善良","美丽","大方","哈哈哈"])
f.close()

3

  • write和writelines的区别:

1、write是传入一个字符串,作为参数
2、writelines是传入一个字符序列
3、注意是字符序列,不能是数字序列

  • 完整格式:
# 打开文件
f = open(r'test.txt', 'w')
# 写入文件
f.writelines(["我超可爱哒", "善良", "美丽", "大方", "哈哈哈"]) # 字符序列
# 刷新缓冲区,保存内容到文件
f.flush()
# 关闭文件
f.close()
  • with open方法:更保险,因为它会自动关闭
with open(r'test.txt', 'w') as f:
    f.writelines(["我超可爱哒", "善良", "美丽", "大方", "哈哈哈"])

三、光标知识点

  • 查看光标tell ;指定光标位置:seek
with open(r'test.txt', 'r') as f:
    print(f.tell())  # 以bytes为单位
    print(f.read())
    print(f.tell())
    f.seek(0)
    print(f.tell())
    f.seek(2)
    print(f.tell())
    print(f.read())

4

命令 作用
read() 读取全部
readline() 每次读取一行内容
read() 读取整个文件的所有行,保存在列表里,列表元素是每一行
r+ 读写,指针在文件开头
w+ 读写,文件名存在则覆盖,文件名不存在则重新创建
a+ 读写,文件名存在则在文件末尾增加,文件名不存在重新创建

四、IO流

临时文件——>内存 ——>IO流

  • 字符流
import io     # 导入io模块
sio = io.StringIO()   # 创建一个对象,进行保存读取

sio.write("hello")    # 写入
print(sio.getvalue())     # 读取  hello

sio.close()    # close之后内容就没有了
  • 字节流(str+list bytes+bytearray)
import io
bio = io.BytesIO()
bio.write(b"hello")        # 写入
print(bio.getvalue())      # 读取  b'hello'
bio.close()      # close

猜你喜欢

转载自blog.csdn.net/qq_34120459/article/details/88038298
今日推荐