开发者

Python file-io code listing current folder path instead of the specified

I have the code:

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)

Located in my music folder ("/home/tom/Music")

When I call it with:

python test.py "/tmp"

I expected it to list my "/tmp" files and folders with the full path. But it printed lines like:

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

This is, the correct file names, but the wrong path (and this files ar开发者_JAVA百科e not either in my Music folder).. What's wrong with this code?


You need to include the full path to the file when you check for existence and print the path:

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...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜