只要有IO,那么就会发生IOError。所以尽量每次都要使用try...finally
#!/usr/bin/env python #-*-coding:utf-8-*- try: f=open("test2.py","r") print f.read() finally: f.close()
但是。我们可以用
with open ("test2.py",‘r‘) as f: print f.read()
同理,写文件:
with open ("test2.py",‘rw‘) as f: f.write("Hello world")
除了文件读写,还有文件夹操作,以及系统操作----OS 模块
import os #用来设置环境变量 os.environ() #显示所有的环境变量 os.envirn.keys() #显示出文件夹和文件名,字符串形式 os.listdir(path) #创建文件夹,移除文件夹 os.mkdir() os.rmdir() #===========os.path模块=============== #路径+文件名==文件所在路径 os.path.join(path,filename) #判断是否是文件夹还是文件 os.path.isdir(path) os.path.isfile(path) #得到文件名 os.path.split(path) #得到文件拓展名 os.path.splitext(path) #可以使用dir(os)来得到os所有的变量和方法 #使用help(os.xxx)来得到具体的用法
编写一个search(s)
的函数,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出完整路径:
#!/usr/bin/env python #-*-coding:utf-*- import os def search(path,name): for x in os.listdir(path): # print x files=os.path.join(path,x) #print files if os.path.isdir(files): #print files search(files,name) elif os.path.isfile(files) and x.find(name)!=-1: print files search("D:\\java","test")
本文出自 “ehealth” 博客,谢绝转载!
原文地址:http://ehealth.blog.51cto.com/10942284/1731804