I have this python script
#!/usr/bin/env python
import datetime, os
from time import gmtime, strftime
to_backup = "/home/vmware/tobackup"
var1 = datetime.datetime.now().strftime('%b-%d-%I%p')
for f in os.listdir(to_backup):
if(os.path.isfile(f)):
print f + " is a file"
if(os.path.isdir(f)):
print f + " is a directory"
It is giving me empty ouput. i don’t know where is the problem
OUTPUT FOR dr jimbob answer
total 36
-rwxrwxr-x 1 vmware vmware 440 May 5 07:41 back.py
-rwxrwxr-x 1 vmware vmware 2624 May 4 20:35 backup.sh
drwxr-xr-x 2 vmware vmware 4096 Jun 22 2010 Desktop
drwxrwxr-x 2 vmware vmware 4096 May 5 03:51 destination
drwxr-xr-x 2 root root 4096 May 4 18:49 public_html
drwxrwxr-x 2 vmware vmware 4096 May 1 07:47 python
-rwxrwxr-x 1 vmware vmware 560 May 1 13:20 regex.py
drwxrwxrwx 7 vmware vmware 4096 May 5 03:50 tobackup
total 20
drwxrwxrwx 2 vmware vmware 4096 May 5 03:50 five
drwxrwxrwx 2 vmware vmware 4096 May 5 03:50 four
drwxrwxrwx 2 vmware vmware 4096 May 5 03:50 one
drwxrwxrwx 2 vmware vmware 4096 May 5 03:50 three
drwxrwxrwx 2 vmware vmware 4096 May 5 03:50 two
Ok you have permission, but you aren’t in the right directory when you list through the files. list_dir gives you a list of dirs/files without their path, and
os.path.isfile('one')andos.path.isdir('one')will check whether the directory ‘one’ exists in the current directory (wherever you launched the script from, unless you explicitly changed directory withos.chdiror included the path, e.g.,os.path.isdir('/home/vmware/tobackup/one').or
or with
walk(but not actually walking through subdirs).EDIT: To be even clearer, the mistake with your original script is you have a file structure like:
When you go to /home/user/bin to run your script (e.g.,
python your_script.py),os.listdir('/home/vmware/tobackup')gives you a list of file and dir names in /home/vmware/tobackup, that is['one','two', ...]. However, when you doos.path.isfile('one')from the directory /home/user/bin, you check to see if/home/user/bin/oneis a file, not whether /home/vmware/tobackup/one is a file. Since/home/user/bin/onedoesn’t exist, you get no output.