我有这个python脚本
#!/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"
它给了我空的输出。我不知道问题出在哪里
输出jimbob博士回答
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
答案 0 :(得分:5)
好的,您有权限,但在列出文件时,您不在正确的目录中。 list_dir为您提供没有路径的目录/文件列表,os.path.isfile('one')
和os.path.isdir('one')
将检查当前目录中是否存在目录“one”(无论您何时从中启动脚本,除非您明确更改)目录os.chdir
或包含路径,例如os.path.isdir('/home/vmware/tobackup/one')
。
#!/usr/bin/env python
import datetime, os
from time import gmtime, strftime
import subprocess
to_backup = "/home/vmware/tobackup"
var1 = datetime.datetime.now().strftime('%b-%d-%I%p')
os.chdir(to_backup)
# os.listdir(to_backup) = ['one', 'two', 'three', 'four', 'five']
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"
或
to_backup = "/home/vmware/tobackup"
var1 = datetime.datetime.now().strftime('%b-%d-%I%p')
# os.listdir(to_backup) = ['one', 'two', 'three', 'four', 'five']
for f in os.listdir(to_backup):
if(os.path.isfile(os.path.join(to_backup,f))):
print f + " is a file"
if(os.path.isdir(os.path.join(to_backup,f))):
print f + " is a directory"
或walk
(但实际上没有穿过子目录)。
to_backup = "/home/vmware/tobackup"
var1 = datetime.datetime.now().strftime('%b-%d-%I%p')
root, dirs, files in os.walk(to_backup).next()
for file in files:
print f + " is a file in " + root
for dir in dirs:
print f + " is a directory"
编辑:为了更清楚,原始脚本的错误是你有一个文件结构:
/home/user/bin/your_script.py
/home/vmware/tobackup/
/home/vmware/tobackup/one
/home/vmware/tobackup/two
...
当您转到/ home / user / bin运行脚本(例如python your_script.py
)时,os.listdir('/home/vmware/tobackup')
会在/ home / vmware / tobackup中为您提供文件和目录名称列表,是['one','two', ...]
。但是,当您从目录/ home / user / bin执行os.path.isfile('one')
时,检查/home/user/bin/one
是否为文件,而不是/ home / vmware / tobackup / one是否为文件。由于/home/user/bin/one
不存在,因此无法输出。
答案 1 :(得分:4)
它适用于我的机器(ubuntu 10.10) 也许/ home / vmware / tobackup是空的,或者你没有权限阅读它。
答案 2 :(得分:2)
os.listdir(dir_name)
返回相对于指定目录的文件名。要在其他命令中使用它们,您需要预先添加目录名称(在循环体的开头通过f = os.path.join(to_backup, f)
),或者在开始循环之前将工作目录更改为备份目录。
这是jimbob博士回答中显示的前两个替代方案。