簡體   English   中英

如何在Python中打印文件列表的絕對路徑?

[英]How can I print the absolute path of a list of files in Python?

我正在嘗試從腳本中的文件打印列表。 但是,以下代碼將打印文件名而不是絕對路徑。

文件位於另一個文件夾時,我需要路徑。 我已經嘗試了其他一些功能,但沒有成功。

這是我的代碼:

ch = []

for file in os.listdir("URL"):
    if file.endswith("ch4.TXT"):
        ch.append(file)

        print ch

我怎樣才能解決這個問題?

使用ospathlib模塊獲取文件的絕對路徑。

import os
import sys


search_path = sys.argv[1] # expects an abspath to dir
ch = []
for file in os.listdir(search_path):
    if file.endswith("ch4.TXT"):
        abs_path = os.path.join(search_path, file)
        ch.append(abs_path)
print ch

訣竅是使用os.path.join()連接組件,並使用os.getcwd()獲取當前的工作目錄。

我將名稱file更改為fname 在Python 2上, file是以別名open

import os
import os.path

ch = []
wd = os.getcwd()
for fname in os.listdir("URL"):
    if fname.endswith("ch4.TXT"):
        ch.append(os.path.join(wd, "URL", fname))

print ch

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM