Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2306090
  • 博文数量: 321
  • 博客积分: 3440
  • 博客等级: 中校
  • 技术积分: 2992
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-24 09:08
个人简介

我就在这里

文章分类

全部博文(321)

文章存档

2015年(9)

2014年(84)

2013年(101)

2012年(25)

2011年(29)

2010年(21)

2009年(6)

2008年(23)

2007年(23)

分类: Python/Ruby

2013-02-27 08:26:28

需求:

你需要在windows系统下设置文件的属性,比如要将文件属性设置为只读,归档等.

讨论:

PyWin32's的win32api模块提供了方法SetFileAttributes,使得这个问题的解决方案变得异常简单: 

import win32con, win32api, os
# create a file, just to show how to manipulate it
thefile = 'test'
f = open('test', 'w')
f.close( )
# to make the file hidden...:
win32api.SetFileAttributes (thefile, win32con.FILE_ATTRIBUTE_HIDDEN)
# to make the file readonly:
win32api.SetFileAttributes(thefile, win32con.FILE_ATTRIBUTE_READONLY)
# to be able to delete the file we need to set it back to normal:
win32api.SetFileAttributes(thefile, win32con.FILE_ATTRIBUTE_NORMAL)
# and finally we remove the file we just made 
os.remove(thefile)

使用win32api.SetFileAttributes的一个好处是可以增强删除文件功能.使用os.remove方法在windows平台上可能会失败,如果文件属性不是默认的情况下.我们可以先使用SetFileAttributes将它设置为默认属性 ,然后删除之.不过需要注意的是,你要清楚的知道自己删除的是什么文件.不要造成不必要的损失.

相关说明:

win32api的文档在:

阅读(3880) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~