Python os模块中的isfile()和isdir()函数均返回false问题解决方法

作者:junjie 时间:2022-04-16 19:40:58 

今天在写一个linux下自动备份指定目录下的所有目录的脚本时,遇到了一个问题,由于我是需要备份目录,所以,需要判断扫描的文件是否为目录,当我用os.path.isdir()来判断的时候,发现所有文件均返回false,刚开始以为是系统兼容性问题,进一步测试,发现用os.path.isfile(),这些文件还是返回false,这肯定就是程序写的有问题了,代码如下:


#!/usr/bin/env python
# a python script to auto backup a directory's file by Hito
import os
Directory=raw_input("Please enter directory you want to backup:")  
dirs=os.listdir(Directory)
for filename in dirs:
 if os.path.isdir(filename):
   os.system("tar czvf "+filename+".tar.gz "+filename)

经过仔细排查,在上面的for/in循环中,filename实际上只是一个文件名。测试发现,当我使用os.path.isdir(目录的绝对路径)的时候,返回的才是true,也就是说,python的isdir()并不像php的is_dir()那样,可以使用当前工作目录的相对路径,那么这里怎么样去改进这个备份文件呢?幸好python提供了一个os.path.join()函数,自动来把需要的路径加到一块,而不用担心手动把路径字符串连接起来时,产生多余的”/”的问题,那么这个备份脚本可以这样写:


#!/usr/bin/env python
# a python script to auto backup a directory's file by Hito
import os
Directory=raw_input("Please enter directory you want to backup:")  
dirs=os.listdir(Directory)
for filename in dirs:
 fulldirfile=os.path.join(Directory,filename)
 if os.path.isdir(fulldirfile):
   os.system("tar czvf "+fulldirfile+".tar.gz "+fulldirfile)
标签:Python,os,isfile(),isdir(),false
0
投稿

猜你喜欢

  • Go语言sort包函数使用示例

    2023-10-15 03:29:59
  • 用MySQL内建复制功能来优化可用性

    2009-02-13 13:55:00
  • PHP面向对象程序设计子类扩展父类(子类重新载入父类)操作详解

    2023-10-15 01:41:57
  • 网页广告 Banner 设计图文手册

    2007-10-18 19:56:00
  • golang中值类型/指针类型的变量区别总结

    2023-09-02 15:07:11
  • Sql Server2005对现有数据进行分区具体步骤

    2008-06-26 13:18:00
  • 简单了解python关键字global nonlocal区别

    2023-07-26 15:47:07
  • 使用IP地址来统计在线人数方法

    2007-08-13 12:51:00
  • 使用 PHP Masked Package 屏蔽敏感数据的实现方法

    2023-09-03 23:49:13
  • Bresenham图形算法JavaScript版本

    2010-01-25 12:09:00
  • 使用ajax开发的五大误区

    2008-09-03 12:46:00
  • 由日文出错的Bug,重新认识 Replace 函数

    2009-07-07 22:28:00
  • MySQL的之表结构修改

    2012-01-05 19:16:17
  • 如何配置一个稳定的SQL Server数据库

    2008-12-09 14:07:00
  • 优化SQL Server的内存占用之执行缓存

    2012-04-13 11:45:06
  • 谈谈网页设计中的字体应用 (3) 实战应用篇·上

    2009-11-24 13:09:00
  • python实现字符串连接的三种方法及其效率、适用场景详解

    2023-07-27 19:57:32
  • 在ASP中使用类,实现模块化

    2008-10-15 14:57:00
  • php基于协程实现异步的方法分析

    2023-06-11 10:08:39
  • 用ASP木马实现FTP和解压缩

    2008-02-13 08:47:00
  • asp之家 网络编程 m.aspxhome.com