简体   繁体   English

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

[英]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.

相关问题 带枚举的基本python file-io变量 - Basic python file-io variables with enumerate Python文件IO和zipfile。 尝试遍历文件夹中的所有文件,然后使用Python遍历各个文件中的文本 - Python file-IO and zipfile. Trying to loop through all the files in a folder and then loop through the texts in respective file using Python 在 Jupyter Notebook 中使用当前文件夹外部的相对路径运行 Python 文件 - Run Python file with relative path outside current folder in Jupyter Notebook 这个获取当前文件路径的 Python 代码将在 Linux 上工作吗? - This Python code to get the current file path will work on Linux? 在当前文件夹中下载excel文件而不是“下载” - Download excel file in current folder instead of "downloads" Python 代码未在 CSV 文件中列出第一行 - Python Code Not Listing First Line in CSV File Python中的文件夹列表 - Folder Listing in Python 获取当前Python文件的路径 - Get the path of the current Python file Python-路径/文件夹/文件创建 - Python - Path/Folder/File creation Python 将文件从当前路径移动到与正在移动的文件命名相似或相似的特定文件夹 - Python move files from current path to specific folder named like or similar to the file being moved
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM