Geomario
Geomario

Reputation: 212

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

I'm trying to print a list from files in my script. However, the following code prints the file names instead of the absolute path.

I need the path while the files are located in another folder. I already tried some other functions without success.

Here's my code:

ch = []

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

        print ch

How can I fix this?

Upvotes: 0

Views: 198

Answers (2)

han solo
han solo

Reputation: 6590

Use the os or pathlib module to get the abspath of the file.

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

Upvotes: 0

cdarke
cdarke

Reputation: 44344

The trick is to use os.path.join() to join the components, and to use os.getcwd() to get the current working directory.

I changed the name file to fname. On Python 2 file is an alias to 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

Upvotes: 0

Related Questions