• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python os模块中的isfile()和isdir()函数均返回false问题解决方法

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

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了os.path.isfile,os.isfile,python os.path.isdir,os.path.isdir,python isfile等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

今天在写一个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)

</div>

经过仔细排查,在上面的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)
</div>

</div>

您可能想查找下面的文章:

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

相关文章

  • Python Web服务器Tornado使用小结
  • python判断字符串是否纯数字的方法
  • python和pyqt实现360的CLable控件
  • 九步学会Python装饰器
  • 简述Python中的面向对象编程的概念
  • Python3读取UTF-8文件及统计文件行数的方法
  • 轻松实现python搭建微信公众平台
  • 编写Python爬虫抓取暴走漫画上gif图片的实例分享
  • phpsir 开发 一个检测百度关键字网站排名的python 程序
  • Python中List.index()方法的使用教程

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python操作RabbitMQ服务器实现消息队列的路由功能
    • python网络编程学习笔记(二):socket建立网络客户端
    • Python实现简易端口扫描器代码实例
    • 详解Django框架中的视图级缓存
    • Python中无限元素列表的实现方法
    • Django的信号机制详解
    • 简单掌握Python的Collections模块中counter结构的用法
    • Python pickle模块用法实例
    • Python字典简介以及用法详解
    • 如何解决django配置settings时遇到Could not import settings 'conf.local'

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有