The Isfile () and Isdir () functions in the Python OS module return false problem resolution _python

Source: Internet
Author: User
Tags python script

Today, when I write a script that automatically backs up all the directories in the specified directory under Linux, I have a problem, because I need to back up the directory, so I need to judge whether the scanned file is a directory, and when I use Os.path.isdir () to judge, I find all the files return false, Initially thought it was a system compatibility problem, further testing, found with Os.path.isfile (), these files or return false, this must be the program has written 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_inpu T ("Please enter your directory want to Backup:")  
dirs=os.listdir (directory) for
filename in dirs:
  if Os.path.isdir (filename):
    os.system ("Tar czvf" +filename+ ". tar.gz" +filename)

After careful investigation, in the for/in loop above, filename is actually just a filename. The test found that when I use Os.path.isdir (the absolute path to the directory), the return is true, that is, the Python isdir () is not the same as PHP's Is_dir (), and can use the relative path of the current working directory. So how do you improve the backup file here? Fortunately Python provides a os.path.join () function that automatically adds the required path to a piece without worrying about creating redundant "/" problems when manually linking the path string, so this backup script can write:

#!/usr/bin/env Python
# A Python script to auto Backup a directory ' s file by Hito
import OS
directory=raw_inpu T ("Please enter directory, 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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.