惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
MongoDB | Blog
MongoDB | Blog
Blog — PlanetScale
Blog — PlanetScale
腾讯CDC
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Apple Machine Learning Research
Apple Machine Learning Research
M
MIT News - Artificial intelligence
人人都是产品经理
人人都是产品经理
Hugging Face - Blog
Hugging Face - Blog
MyScale Blog
MyScale Blog
小众软件
小众软件
博客园 - 三生石上(FineUI控件)
N
Netflix TechBlog - Medium
阮一峰的网络日志
阮一峰的网络日志
博客园 - Franky
Recent Announcements
Recent Announcements
A
About on SuperTechFans
Stack Overflow Blog
Stack Overflow Blog
The GitHub Blog
The GitHub Blog
D
Docker
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - ________囧丶殇

django系列 - 安装和新建项目 SQL - 基础 javascript刷新父页面 SQL - 约束 C语言(8) - 反转单向链表 C语言(7) - 数据结构之单向链表 C语言(6) - 各种排序算法的比较 C语言(5) - 选择排序 快速排序 C语言(4) - 插入排序 C语言(3) - 冒泡排序 归并排序 C语言(2) - 从指针开始 C语言(1) - 开始之前 python实践 - 抓取网页中的图片和数据 python实践 - 下载文件 python补充(2) - 内置函数 python补充(1) python笔记(九) - 类 part2 python笔记(八) - 类 part1 python笔记(七) - and和or
python笔记(十) - 异常和文件处理
________囧丶殇 · 2009-04-27 · via 博客园 - ________囧丶殇

 1.打开一个不存在的文件:

try:
      f 
= open('demon.txt','w')
      
#print s
except IOError:
      
print 'file is not exits!'
except:
      
print 'other exception'
else:
      
print 'file exits!' 

用trt...exceot不捕获异常。如果没有异常发生,则执行else后面的内容

和C#一样,python捕获异常也是按照顺序的,上例中,先捕获IOError异常,如果没有写明异常类型则捕获所有的异常,你去可去掉第三行的#会发生什么。

2.上例中,我们使用open打开了一个文件,这个方法可以接受三个参数,文件名,模式和缓冲区,打开文件的模式有三种:‘r’-只读模式,也是默认模式,'w'-写模式,'a'-追加模式

在写模式和追加模式两种情况下,如果文件不存在会自动创建文件,读模式则会抛出异常

>>> f = open('demon.txt','w')
>>> f.write('line1')
>>> f.close()
>>> file('demon.txt').read()
'line1' 

3.接下来看看OS模块

>>> import os
>>> os.path.join("c:\\music\\ap\\""mahadeva.mp3")  
'c:\\music\\ap\\mahadeva.mp3'
>>> os.path.join("c:\\music\\ap""mahadeva.mp3")   
'c:\\music\\ap\\mahadeva.mp3'
>>> os.path.expanduser("~")                         
'c:\\Documents and Settings\\mpilgrim\\My Documents'
>>> os.path.join(os.path.expanduser("~"), "Python"
'c:\\Documents and Settings\\mpilgrim\\My Documents\\Python'

 expanduser 将对使用 ~ 来表示当前用户根目录的路径名

4.分割路径

>>> os.path.split("c:\\music\\ap\\mahadeva.mp3")                        
(
'c:\\music\\ap''mahadeva.mp3')
>>> (filepath, filename) = os.path.split("c:\\music\\ap\\mahadeva.mp3"
>>> filepath                                                            
'c:\\music\\ap'
>>> filename                                                            
'mahadeva.mp3'
>>> (shortname, extension) = os.path.splitext(filename)                 
>>> shortname
'mahadeva'
>>> extension
'.mp3'

 5.列出所有文件

>>> os.listdir("c:\\music\\_singles\\")              
[
'a_time_long_forgotten_con.mp3''hellraiser.mp3',
'kairo.mp3''long_way_home1.mp3''sidewinder.mp3'
'spinning.mp3']
>>> dirname = "c:\\"
>>> os.listdir(dirname)                              
[
'AUTOEXEC.BAT''boot.ini''CONFIG.SYS''cygwin',
'docbook''Documents and Settings''Incoming''Inetpub''IO.SYS',
'MSDOS.SYS''Music''NTDETECT.COM''ntldr''pagefile.sys',
'Program Files''Python20''RECYCLER',
'System Volume Information''TEMP''WINNT']
>>> [f for f in os.listdir(dirname)
if os.path.isfile(os.path.join(dirname, f))] 
[
'AUTOEXEC.BAT''boot.ini''CONFIG.SYS''IO.SYS''MSDOS.SYS',
'NTDETECT.COM''ntldr''pagefile.sys']
>>> [f for f in os.listdir(dirname)
 
if os.path.isdir(os.path.join(dirname, f))]  
[
'cygwin''docbook''Documents and Settings''Incoming',
'Inetpub''Music''Program Files''Python20''RECYCLER',
'System Volume Information''TEMP''WINNT']

 listdir 函数接收一个路径名,它返回那个目录的内容的一个 list

6.

>>> dirname = 'c:\\'
>>> [os.path.normcase(f) for f in os.listdir(dirname)]
[
'adclog''autoexec.bat''boot''boot.bak''boot.ini''bootfont.bin''config.msi''config.sys''cygwin''documents and settings''download''downloads''ftc2008''grldr''img''inetpub''io.sys''krecycle''menu.lst''msdos.sys''msocache''ntdetect.com''ntldr''pagefile.sys''program files''python26''recycler''system volume information''windows']
>>> [os.path.join(dirname,f) for f in os.listdir(dirname) if os.path.splitext(f)[1in ['.ini']]
[
'c:\\boot.ini']
>>> 

 我们使用 os.path.normcase(f) 根据操作系统的缺省值对大小写进行标准化处理

7.一种更强大的方法

>>> import glob
>>> glob.glob('c:\\*.ini')
[
'c:\\boot.ini']
>>> 

 它查找出在C目录下所有的.ini文件