2007-07-30

 

Python Cookbook 2.25 在Windows系统上改变文件属性

需求:

你需要在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的文档在:

http://ASPN.ActiveState.com/ASPN/Python/Reference/Products/ActivePython/PythonWin32Extensions/win32file.html



Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?