IO编程

(1)常用命令
from sys import argv
form os.path import exists
命令行运行程序 带参数:
script,filename=argv
文件操作相关命令:
close:关闭文件
open:打开文件
read:读取文件内容
readline:读取文本文件中的一行
readlines:读取文件所有的行,返回list
truncate:清空文件
write("stuff"):将stuff写入文件

(2)IO操作
同步IO:CPU和内存等着外设的执行
异步IO:CPU和内存在外设执行的时候去执行其他其他任务
try:
f=open('/path/to/file','r')
print(f.read())
finally:
if f:
f.close()

with open('/path/to/file','r') as f:
print(f.read())

read():一次性读取文件全部内容,read(size),多次分段读取大文件的内容;
readline():每次读取一行内容;
readlines():一次读取文件所有内容并按行返回list
for line in f.readlines():
print(line.strip()) # 把末尾的 删掉

读取UTF-8编码的二进制文件:f=open('/path/to/file','rb')
读取UTF-8编码的文件:f=open('/path/to/file','r',encoding='gbk',errors='ignore') # 忽略编码错误

写文件时,调用open方法,传入标识符'w'、'wb'分别表示写文本文件、二进制文件
'a':以追加模式写入
fo=open('test.txt','w',encoding='uft-8') # test.txt 不存在,则新建
fo.write('啦啦啦')
fo.close() #写文件时,os不会立刻把数据写入磁盘,而是放到内存缓存起来,空闲的时候再慢慢写入。
#只有调用close()方法时,操作系统才保证把没有写入的数据全部写入磁盘
fo=open('test.txt','a',encoding='uft-8') # 在文件中追加内容
fo.write(' 这是追加的内容')
fo.close()

(3)IO内存操作
StringIO:在内存中读写str
from io import StringIO
f=StringIO('Hello! Hi! Goodbye!')
print(f.getvalue()) # 获取写入后的str
while True:
s=f.readline()
if s=='':
break
print(s.strip())

BytesIO:在内存中读写bytes
from io imprt BytesIO
f=BytesIO()
f.write('中文'.encode(''UTF-8))
print(f.getvalue())

(4)OS常用
import os
os.name # posix:linuxunixmac nt:windows
os.environ # 查看操作系统中定义的环境变量
os.environ.get('PATH') # 查看PATH环境变量
os.path.abspath('.') # 查看当前目录的绝对路径
os.path.join('/User/michael','testdir') # 在某个目录下创建一个新目录(兼容不同操作系统),首先把新目录的完整路径表示出来
os.mkdir('/User/michael/testdir') # 然后创建一个目录
os.rmdir('/User/michael/testdir') # 删掉一个目录
os.path.split('/User/michael/testdir/file.txt') # 拆分路径,后一部分是最后级别的目录或 文件名
os.path.splitext('/User/michael/testdir/file.txt') # 直接得到文件扩展名
拆分、合并路径的函数只是对字符串进行操作,不要求目录和文件真实存在
os.rename('test.txt','test.py') # 文件重命名
os.remove('test.py') # 删除文件
os.isabs(path) # 判断是否是绝对路径
os.path.exists(path) # 检验给出的拉路径是否真的存在
os.path.basename(path) # 获取文件名
os.path.dirname(path) # 获取路径名
shutil模块提供了copyfile()的函数来复制文件,可以把它看做os模块的补充

# 列出当前目录下所有的目录
[x for x in os.listdir('.') if os.path.isdir(x)]
# 列出所有的.py文件
[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext[1]=='.py']
原文地址:https://www.cnblogs.com/xyl-share-happy/p/8283717.html