Python file-io代码列出当前文件夹路径而不是指定的

时间:2010-12-24 22:13:27

标签: python file file-io

我有代码:

import os
import sys

fileList = os.listdir(sys.argv[1])
for file in fileList:
    if os.path.isfile(file):
        print "File >> " + os.path.abspath(file)
    else:
        print "Dir >> " + os.path.abspath(file)

位于我的音乐文件夹(“/ home / tom / Music”)

当我打电话给:

python test.py "/tmp"

我希望它能以完整路径列出我的“/ tmp”文件和文件夹。但它打印的行如:

Dir >> /home/tom/Music/seahorse-gw2jNn
Dir >> /home/tom/Music/FlashXX9kV847
Dir >> /home/tom/Music/pulse-DcIEoxW5h2gz

这是正确的文件名,但路径错误(这些文件不在我的音乐文件夹中)。这段代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

检查存在时,您需要包含文件的完整路径并打印路径:

dir = sys.argv[1]

fileList = os.listdir(dir)
for file in fileList:
    file = os.path.join(dir, file)  # Get the full path to the file.
    # etc...
相关问题