Kanika Singh
Kanika Singh

Reputation: 87

How to append files names with the path in python?

I have path variable path = 'C:\Users\Sony\Desktop', now I am finding all the text files in this directory and saving their names in a list by this code :

text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
print text_files

This will give me ['a.txt', 'b.txt', 'k.txt', 'link.txt']

Now I want to open these files one by one to find a word , for tht I need full

url=["C:\Users\Sony\Desktop\a.txt","C:\Users\Sony\Desktop\b.txt","C:\Users\Sony\Desktop\k.txt","C:\Users\Sony\Desktop\link.txt"]

how to append path with the file name , when I do url=path+'\'+text_files[0] then I get error , '\' is taken as escape, plz help

Upvotes: 0

Views: 6972

Answers (2)

work.bin
work.bin

Reputation: 1108

You will have to escape the backslash since it is a special character.
url=path+'\\'+text_files[0]

Read more about escape sequences here

However, if portability of your Python script (across OSs) is important for you then use os.path.join().

Upvotes: 0

Jableader
Jableader

Reputation: 33

Try text_files = [os.path.join(path, name) for name in text_files]

You can find more on the path module here: https://docs.python.org/2/library/os.path.html

Upvotes: 2

Related Questions