python文件操作和os模块

文件操作

读取文件

语法:

open(file,mode)
mode 释义
r read 读
w weite 写
b binary 二进制

read() 读取所有内容

mode默认是rt,文本文件
如果文件找不到会报错

stream = open(r'C:\Users\inmeditation\Desktop\test\1.txt')
container = stream.read()
print(container)
11111
22222
33333

readline() 每次读取一行内容

stream = open(r'C:\Users\inmeditation\Desktop\test\1.txt')
while True:
    container = stream.readline()
    print(container,end='')
    if not container:
        break
11111
22222
33333

默认读取每行都会有一个回车,所以将每次打印后的回车取消

readlines() 读取所有的行保存到列表中

stream = open(r'C:\Users\inmeditation\Desktop\test\1.txt')
lines = stream.readlines()
print(lines)
['11111\n', '22222\n', '33333']

readable() 判断是否可读

stream = open(r'C:\Users\inmeditation\Desktop\test\1.txt')
container = stream.readable()
print(container)
True

当读取一个非文本文件

stream = open(r'C:\Users\inmeditation\Desktop\test\11.png','rb')
con = stream.read()
print(con)
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\

在控制台无法输出图片

文件写操作

write(内容) 每次都会将原来的内容清空,然后写当前的内容

close()释放资源

stream = open(r'C:\Users\inmeditation\Desktop\test\1.txt','w')
s = '''
你好!
    欢迎来到澳门博彩赌场,赠送给你一个金币!
                        赌王:高进
'''
result = stream.write(s)
stream.close()

查看文件


你好!
    欢迎来到澳门博彩赌场,赠送给你一个金币!
                        赌王:高进

发现文件之前的内容被清空了

writelines(Iterable) 放一个可迭代的内容,比如列表.

没有换行机制

stream = open(r'C:\Users\inmeditation\Desktop\test\1.txt','w')
s = ['赌神高进','赌侠小刀','赌圣周星驰']
result = stream.writelines(s)
stream.close()
赌神高进赌侠小刀赌圣周星驰

追加文件

stream = open(r'C:\Users\inmeditation\Desktop\test\1.txt','a')
s = '僵尸先生'
result = stream.write(s)
stream.close()
赌神高进赌侠小刀赌圣周星驰僵尸先生

文件的复制

with结合open使用,可以帮助我们自动释放资源

with open(r'C:\Users\inmeditation\Desktop\test\11.png','rb') as stream:
    container = stream.read()
    with open(r'C:\Users\inmeditation\Desktop\test2\11.png','wb') as wstream:
        wstream.write(container)

执行完毕后,test2目录下多了一个文件11.png

os模块

猜你喜欢

转载自www.cnblogs.com/inmeditation/p/12397855.html