r只读, r+读写, w写入(覆盖), w+读写(覆盖), a追加, a+读追加, rb, rb+, wb, wb+, ab, ab+ 二进制模式
f = open('文件.py', 'r', encoding='utf-8')
print(f.read())
f.close()
f = open('abc.txt', 'w+', encoding='utf-8')
f.write('hello world')
指针回到开头
f.seek(0)
print(f.read())
f.close()
readline 读取一行 readlines 读取所有行 write 写入 writelines 写入多行(需要自己加换行符)
f = open('abc.txt', 'w+', encoding='utf-8')
f.writelines(['hello world', '\n', 'hello python', '\n'])
f.seek(0)
print(f.readlines())
with open…as… 自动关闭
with open('abc.txt', 'w+', encoding='utf-8') as f:
f.write('hello world')
f.seek(0)
print(f.read())
处理图片
import requests
url = 'https://gips1.baidu.com/it/u=2109130335,2323458671&fm=3028&app=3028&f=PNG&fmt=auto&q=100&size=f1296_198'
res = requests.get(url)
print(res.content)
with open('abc.png', 'wb') as f:
f.write(res.content)
url = 'https://audio04.dmhmusic.com/71_53_T10064861651_128_4_1_0_sdk-cpm/cn/0513/M00/5A/AB/ChAKFGahzHmAFTV6AFL8LE8Llrk011.mp3?xcode=f12f36cd37b25981e3fde4a2aa6f28ff5c8883c'
res = requests.get(url)
print(res.content)
with open('abc.mp3', 'wb') as f:
f.write(res.content)
忽略错误
with open('abc.txt', 'w', encoding='gbk') as f:
f.write("你好python")
with open('abc.txt', 'r', encoding='ascii', errors='ignore') as f:
print(f.read())
io 模块
import io
f = io.StringIO()
f.write('hello world')
print(f.getvalue())
os 模块
import os
print(os.getcwd())
print(os.listdir('.'))
print(os.path.exists('abc.txt'))
print(os.system('dir'))
print(os.chdir('c:\\'))
os.mkdir('abc')
os.rmdir('abc')
os.rename('abc', 'abc1')
print(os.remove('abc.txt'))
print(os.path.getsize('abc.txt'))
print(os.path.getatime('abc.txt'))
print(os.path.getmtime('abc.txt'))
print(os.path.getctime('abc.txt'))
print(os.path.join('c:\\', 'abc.txt'))
print(os.path.isdir('c:\\'))
print(os.path.isfile('c:\\'))
print(os.path.isabs('c:\\'))