1.文件写操作
""" open(name , mode) name: 文件名 是一个字符串 mode:操作文件的模式 r = read: 读 w = write: 写 b = binary: 二进制 a = append: 追加模式 +: 凡是有+的 可以读写 """ # 打开一个文件 没有mode则默认是r读模式 # 使用w写入的模式打开 如果没有这个文件则自动创建这个文件 # 如果使用r的模式打开没有这个文件则报错 f = open("1.txt", mode="w") # 2.写入文件 f.write("hello python today is sunny") # 3.关闭文件 运行之后检查一下内容是否写入 f.close()
2.文件读操作
""" open(name , mode) name: 文件名 是一个字符串 mode:操作文件的模式 r = read: 读 w = write: 写 b = binary: 二进制 a = append: 追加模式 +: 凡是有+的 可以读写 """ # 打开一个文件 没有mode则默认是r读模式 # 使用w写入的模式打开 如果没有这个文件则自动创建这个文件 # 如果使用r的模式打开没有这个文件则报错 f = open("1.txt", mode="w") # 2.写入文件 f.write("hello python today is sunny") # 3.关闭文件 运行之后检查一下内容是否写入 f.close()
3.读取多行数据
# 打开文件 f = open("1.txt", mode="r") # 读取多行数据 返回一个列表 content = f.readlines() # 得到的是列表 每一行是一个元素 print(content, type(content)) # 关闭文件 f.close()
4.一行一行读取数据
# 打开文件 f = open("1.txt", mode="r") # 读取一行数据 content = f.readline() # 读取第一行数据 返回的是字符串 print(content, type(content)) # 读取一行数据 content1 = f.readline() # 读取第一行数据 返回的是字符串 print(content1, type(content1)) # 读取一行数据 content2 = f.readline() # 读取第一行数据 返回的是字符串 print(content2, type(content2)) # 关闭文件 f.close()