Python 文件输入输出代码列出当前文件夹路径而不是指定路径

1 投票
1 回答
944 浏览
提问于 2025-04-16 09:00

我有一段代码:

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

在检查文件是否存在的时候,你需要提供文件的完整路径,并且打印出这个路径:

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

撰写回答