Both the isfile of and isdir of functions in the Python OS module return false

  • 2020-04-02 14:33:28
  • OfStack

Today in to write a Linux under the automatic backup of all directories in the directory specified script, encountered a problem, because I need backup directory is, therefore, need to decide whether scanning file is a directory, when I use OS. The path. The isdir () to determine, found that all documents are false, and at first thought is the system compatibility issues, further tests, found in OS. Path. Isfile (), these files are still returns false, this must be written program has a problem, the code is as follows:


#!/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)

On careful examination, in the for/in loop above, filename is really just a filename. The test found that true only returned when I used os.path.isdir(the absolute path to the directory), which means that python's isdir() does not use the relative path to the current working directory as PHP's is_dir() does. Fortunately, python provides an os.path.join () function to automatically add the required paths together without worrying about the extra "/" problem when manually concatenating the path strings.


#!/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)


Related articles: