(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()) # 把末尾的\n 删掉 读取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('\n这是追加的内容') fo.close()(3)IO内存操做 StringIO:在内存中读写str from io import StringIO f=StringIO('Hello!\nHi!\nGoodbye!') 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:linux\unix\mac 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']