Python3-文件操作
一、open()-----read()
1 stream = open(r"F:\FileOperation\lyrics.txt")
2 container = stream.read()
3 print(container)
4
5 print("-"*30)
6
7 stream = open(r"F:\FileOperation\lyrics.txt") # 默认r
8 containerable = stream.readable() # 判断是否可读
9 if containerable:
10 while True:
11 container = stream.readline() # 读取一行
12 print(container)
13 if not container:
14 break
15
16 print("-"*30)
17
18 stream = open(r"F:\FileOperation\lyrics.txt")
19 container = stream.readlines() # 读取多行
20 for i in container:
21 print(i)
22
23
24 stream = open(r"F:\FileOperation\demoDaoJi.jpg",'rb') # 图片mode应为'rb'
25 containerable = stream.readable()
26 if containerable:
27 container = stream.read()
28 print(container)
二、open()----write()
1 stream = open(r"F:\FileOperation\magic.txt",'w')
2 # magic.txt原内容:Sweetmagic
3 containerable = stream.writable() # 判断是否可写
4 if containerable:
5 container = stream.write("Hello World")
6 # write()每次都会将原来的内容清空,然后写入当前的内容
7 stream.close() # 此时内容:Hello World
8 # container = stream.write("Hello kitty")
9 # ValueError: I/O operation on closed file.
10 # 每次只要经过close()操作,无法再写入
11
12 stream = open(r"F:\FileOperation\magic.txt",'w') # 原内容:Hello World
13 stream.writelines(["Sweet Magic\n","Sakura\n","Seele\n"]) # writelines()并没有换行效果,需要手动加"\n"
14 stream.close()
15 """
16 此时内容:
17 Sweet Magic
18 Sakura
19 Seele
20 """
21
22 stream = open(r"F:\FileOperation\sweet.txt",'a')
23 # sweet.txt原内容:Hello World ,'a'-->append,追加,在原内容后面追加新内容
24 stream.write("Sweet Magic")
25 stream.close() # 此时内容:Hello WorldSweet Magic
三、复制
with open(r"F:\FileOperation\p1\demoDaoJi.jpg",'rb') as stream:
container = stream.read()
with open(r"F:\FileOperation\p2\demoDaoJi.jpg",'wb') as wstream:
wstream.write(container)
print("文件复制完成!")