Python 强大而易用的文件操作(转载)

在Python中可以很方便地做一些诸如浏览目录,创建文件夹,删除文件夹等等的操作。

对文件系统的访问大多通过os模块来实现,因为Python是多平台的,os模块只是前端,具体的实现还是由具体的系统来完成,这里还是主要说Windows系统。

利用os模块可以做创建文件,删除文件,重命名文件,返回文件信息等等。

os.path模块中则可以得到文件名,目录路径,或者文件是否存在,文件的大小等等信息。

要使用这个模块,就必须先把它导入。

  1. importos

可以用os.path模块中的isdir()函数来看看指定路径是不是存在,是不是一个目录。

  1. os.path.isdir('C:\Windows')

Python会返回True,表示目录存在。如果把上面的Windows改成不存在的目录比如Windows1,就会返回False

用os模块中的chdir()可以改变当前的目录,为下一步操作做准备。 改变目录后,可以用getcwd()函数得到现在的目录。 用listdir()函数可以得到目录中的所有文件和文件夹的名称,以列表的形式储存。

  1. os.chdir(dir)    # 括号内的dir为要改变的目录,例如os.chdir('C:\Windows')
  2. cwd=os.getcwd()   # 得到目前的目录名
  3. os.listdir(cwd)   # cwd为要显示的目录。

以下是一个具体的应用:

  1. >>> importos
  2. >>> os.path.isdir('c:\windows')
  3. True
  4. >>> os.chdir('c:\windows')
  5. >>> cwd=os.getcwd()
  6. >>> print cwd
  7. c:\windows
  8. >>> os.listdir(cwd)
  9. ['Acronis', 'addins', 'AppCompat', 'AppPatch', 'assembly', 'avastSS.scr', 'AxIns
  10. tSV', 'bfsvc.exe', 'BitLockerDiscoveryVolumeContents', 'BOCNET', 'Boot', 'bootst
  11. at.dat', 'Branding', 'CSC', 'Cursors', 'debug', 'diagnostics', 'DigitalLocker',
  12. 'DirectX.log', 'Downloaded Installations', 'Downloaded Program Files', 'DPINST.L
  13. OG', 'DtcInstall.log', 'ehome', 'en-US', 'Enterprise.xml', 'explorer.exe', 'Font
  14. s', 'fveupdate.exe', 'Globalization', 'Help', 'HelpPane.exe', 'hh.exe', 'idmfsa.
  15. dll', 'IE9_main.log', 'IME', 'inf', 'Installer', 'L2Schemas', 'LiveKernelReports
  16. ', 'Logs', 'Media', 'mib.bin', 'Microsoft.NET', 'ModemLogs', 'msdfmap.ini', 'not
  17. epad.exe', 'nsreg.dat', 'ntbtlog.txt', 'Offline Web Pages', 'Options', 'Panther'
  18. , 'PCHEALTH', 'Performance', 'PFRO.log', 'PLA', 'PolicyDefinitions', 'Prefetch',
  19.  'regedit.exe', 'Registration', 'RemotePackages', 'rescache', 'Resources', 'RtlE
  20. xUpd.dll', 'SchCache', 'schemas', 'security', 'ServiceProfiles', 'servicing', 'S
  21. etup', 'setupact.log', 'setuperr.log', 'ShellNew', 'SoftwareDistribution', 'Spee
  22. ch', 'splwow64.exe', 'Starter.xml', 'system', 'system.ini', 'System32', 'SysWOW6
  23. 4', 'TAPI', 'Tasks', 'Temp', 'tracing', 'TSSysprep.log', 'twain.dll', 'twain_32'
  24. , 'twain_32.dll', 'twunk_16.exe', 'twunk_32.exe', 'Vss', 'Web', 'win.ini', 'Wind
  25. owsShell.Manifest', 'WindowsUpdate.log', 'winhlp32.exe', 'winsxs', 'WMSysPr9.prx
  26. ', 'write.exe', 'xinstaller.dll', 'xinstaller.exe', 'zh-CN']
  27. >>> os.listdir(cwd)[0]
  28. 'Acronis'

其他文件系统操作:

  1. os.mkdir('e:\\abcd')  # 之所以打两个斜杠,是因为要取消\a的转义。mkdir()在这里在e盘创建一个名字为abcd的文件夹。
  2. os.rmdir('e:\\abcd')  # rmdir()删除e盘名字为abcd的文件夹。
  3. os.remove(filename)   # 删除文件。
  4. os.stat(filename)     # 得到文件的信息。

os.path也有一些其他的操作,例如basename()去掉路径,返回文件名,dirname()去掉文件名,返回路径等等。到时候可以再查有关书籍。

posted @ 2013-07-22 13:48  voss  阅读(930)  评论(0编辑  收藏  举报