1.打开文件
f = open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
参数:
file : 要打开的文件的名字 (或者数偶数路径)
绝对路径:唯一的,完整的路径,从盘符开始
ctrl+shift+c
python 也可以用 / 表示路径
推荐使用 /
相对路径:
demo.txt
day15\demo.txt
r"" 转义失效
2.关闭
f.read()
f.close()
with open ... as 语句
f = open(fileNmae)
f.close
with open(fileName) as f:
pass
3.读取
fileName = 'day15/demo.txt'
with open(fileName) as f:
content = f.read()
print(content)
fileName = 'day15/demo2.txt'
with open(fileName,encoding='utf-8') as f:
content = f.read()
print(content)
read(n) 该参数用来指定要读取的字符的数量
可以接力读,如果读完了,返回空字符串
fileName = 'day15/demo2.txt'
with open(fileName, encoding='utf-8') as f:
content = f.read(4)
print(content)
content = f.read(4)
print(content)
content = f.read(4)
print(content)
content = f.read(4)
print(content)
content = f.read(4)
读取大文件的方式
fileName = 'day15/demo2.txt'
with open(fileName, encoding='utf-8') as f:
all_content =''
size = 2
while True:
content = f.read(size)
if content == '':
break
print(all_content)
readlines(): 一行一行的读取内容,按行存储列表中
4.写入
write()
打开模式:读 写 追加
r : 只读
w : 可写_覆盖 (默认覆盖文件,如果文件不存在会创建文件)
a : 可写_追加 (直接追加内容,如果文件不存在也会创建文件)
fileName = 'day15/demo4.txt'
with open(fileName,'w',encoding='utf-8') as f:
f.write('你好世界\n')
with open(fileName,'a',encoding='utf-8') as f:
f.write('你好世界\n')
+ : 为操作符增加功能
r+ : 可读也可写,文件不存在会报错
w+ : 可写也可读
a+ : 可写也可读
2.二进制文件
读取模式参数
t 读取文本文件(默认值)
b 读取二进制文件
fileName = r'C:\Users\Administrator\Desktop\周杰伦 - 晴天.mp3'
with open(fileName, 'rb') as f:
new_path = 'qq.mp3'
with open(new_path, 'ab') as new_f:
size = (1024*8) * 100
while True:
content = f.read(size)
if content == b'':
break
new_f.write(content)