【python基础】文件操作open简介

mode:

  • r: read 读操作,纯文本文件;

  • w:write 写操作,纯文本文件;

  • rb: binary 读二进制;

  • wb:binary 写二进制

  • read 读取所有内容

  • readline 每次读取一行内容

  • readlines 读取所有保存在列表中

  • readable 是否可读,返回true or false

open(file, mode='r')

Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)
    ========= ===============================================================
stream = open(r'C:\Users\lizhu.ding\Desktop\aa.txt')
container = stream.read()
print(container)

输出文件中的内容

line = stream.readline() #逐行读取

循环读取,每行后面会有一个空行

while True:
    line= stream.readline()
    print(line)
    if not line:
        break
 lines = stream.readlines()
 print(lines)# 保存在列表中   

w mode
write 每次都会先把原来的内容清空,再写当前的内容,后面不会加空行
writelines 可迭代的,不会换行

stream = open(r'C:\Users\lizhu.ding\Desktop\aa.txt','w')
s = '''
你好,欢迎来到游乐园
请买门票。

'''
container = stream.write(s) # 写文件时会把原文件覆盖
stream.writelines(['ddd','eeee'])
# a mode
# 追加模式,不会清空

stream = open(r'C:\Users\lizhu.ding\Desktop\aa.txt','a')
s = '''
你好,欢迎来到游乐园
请买门票。

'''
container = stream.write(s) # 写文件时不会把原文件覆盖,继续追加
stream.writelines(['ddd','eeee'])

你可能感兴趣的:(python基础,python,stream)