[英]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") 位于我的音乐文件夹中(“ / 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. 我希望它列出具有完整路径的“ / tmp”文件和文件夹。 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 are 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...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.