tags:

views:

65

answers:

3

I'm using os.listdir() to get all the files from a directory and dump them out to a txt file. I'm going to use the txt file to import into access to generate hyperlinks. The problem I'm having is getting the correct path. So when the script is ran it uses whatever directory you are in. Here is an example. Right now it half works, it create links.txt, but there is nothing in the text file.

myDirectory = os.listdir("links")
f.open("links.txt", "w")
f.writelines([os.getcwd %s % (f) for f in myDirectory])
A: 

You have to call os.getcwd() with the trailing parens.

What you probably actually want here though is os.path.join()

Paul McMillan
+1  A: 

This line of yours:

f.writelines([os.getcwd %s % (f) for f in myDirectory])

is invalid Python syntax and it's very hard to guess what you had in mind for it -- for example, why would you care about the current directory when myDirectory lists, not files in the current directory, but rather files in subdirectory "links"?

Trying to read your mind is always a difficult and generally unrewarding exercise, but assuming you do mean to use the current directory, you might want

 f.writelines(os.path.join(os.getcwd(), f) for f in myDirectory)
Alex Martelli
That did it. Sorry for making you a jedi on that one. I'm still learning programing.
Dunwitch
A: 

os.getcwd is a function you need to call... also I'm not sure what you're doing with the string escape % - but they only work inside strings... I'm guessing you want something like this:

f.writelines([os.path.join(os.getcwd(),f) for f in myDirectory])

[Edit: os.path.join from Alex Martelli's better answer]

thrope