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)