@Frankchen
2016-03-28T08:10:29.000000Z
字数 2879
阅读 1423
python
os 和 os.path 模块包括许多与文件系统交互的函数。 shutil 模块能copy文件。
filenames = os.listdir(dir)
--在此路径下的文件名os.path.join(dir, filename)
--dir和filename创造yigepathos.path.abspath(path)
--返回path的绝对路径os.path.dirname(path), os.path.basename(path)
--给予 dir/foo/bar.html的情况下,分别返回"dir/foo"和"bar.html"os.path.exists(path)
--如果存在返回Trueos.mkdir(dir_path)
--产生一个dir,os.makedirs(dir_path)
返回所有需要的dirshutil.copy(source-path, dest-path)
--copy一个文件
## Example pulls filenames from a dir, prints their relative and absolute paths
def printdir(dir):
filenames = os.listdir(dir)
for filename in filenames:
print filename ## foo.txt
print os.path.join(dir, filename) ## dir/foo.txt (relative to current dir)
print os.path.abspath(os.path.join(dir, filename)) ## /home/nick/dir/foo.txt
commands 模块是一种简单的运行外部命令并且抓取它的输出的方法。
(status, output) = commands.getstatusoutput(cmd)
--运行command,等待退出,返回其状态码和输出文字为tuple。output = commands.getoutput(cmd)
--和上面一样,但是没有状态码commands.getstatus()
--这个比较奇怪,尽量不要使用popen2
--此模块能给更多的控制os.system(cmd)
运行command并且把它的输出作为你的输出,并返回错误码。当你需要运行command但是不需要把它的输出写入python数据结构时候适用。
## Given a dir path, run an external 'ls -l' on it --
## shows how to call an external program
def listdir(dir):
cmd = 'ls -l ' + dir
print "Command to run:", cmd ## good to debug cmd before actually running it
(status, output) = commands.getstatusoutput(cmd)
if status: ## Error case, print the command's output to stderr and exit
sys.stderr.write(output)
sys.exit(1)
print output ## Otherwise do something with the command's output
一个exception代表一个在某行代码中阻止常规运行的 run-time错误并把控制转向错误码。比如,run-time错误可能是因为程序中用到的某个变量没有值(ValueError),或者文件打开操作错误因为那儿没有这个文件存在(IOError)。
没有error handing 代码,一个 run-time exception只是暂停程序并且返回错误信息,而我们可以添加'try/except'结构来解决exception如:
try:
## Either of these two lines could throw an IOError, say
## if the file does not exist or the read() encounters a low level error.
f = open(filename, 'rU')
text = f.read()
f.close()
except IOError:
## Control jumps directly to here if any of the above lines throws IOError.
sys.stderr.write('problem reading:' + filename)
## In any case, the code then continues with the line after the try/except
try部分包括了可能跑出exception的代码。而except部分保持代码运行如果那里有exception,若没有exception,except部分被跳过。
urllib模块提供了url取得:让一个url看起来像能读取的文件
。urlparse 能切分合并url。
le = urllib.urlopen(url)
--返回一个对象文件text = ufile.read()
--读取文件(readlines()也可以)info = ufile.info()
--关于url内容的meta-infobaseurl = ufile.geturl()
-- 返回"base" urlurllib.urlretrieve(url, filename)
--下载url到指定文件路径urlparse.urljoin(baseurl, url)
--
## Given a url, try to retrieve it. If it's text/html,
## print its base url and its text.
def wget(url):
ufile = urllib.urlopen(url) ## get file-like object for url
info = ufile.info() ## meta-info about the url content
if info.gettype() == 'text/html':
print 'base url:' + ufile.geturl()
text = ufile.read() ## read all its text
print text
上面的代码不包括错误handling,下面加上try/except:
## Version that uses try/except to print an error message if the
## urlopen() fails.
def wget2(url):
try:
ufile = urllib.urlopen(url)
if ufile.info().gettype() == 'text/html':
print ufile.read()
except IOError:
print 'problem reading url:', url