1

I have one folder say ABC in which i have so many files with extension say 001.py, 001.xls, 001.pdf and many more. I want to write one program in which we get list with this filename say

 ["C:\Users\Desktop\ABC\001.py", "C:\Users\Desktop\ABC\001.xls", "C:\Users\Desktop\ABC\001.pdf"]

MyCode:

import os
from os import listdir
from os.path import isfile, join

dir_path = os.path.dirname(os.path.realpath(__file__))
print(dir_path) #current path

cwd = os.getcwd()
list3 = []
onlyfiles = [f for f in listdir(cwd) if isfile(join(cwd, f))]
for i in onlyfiles:
    list3.append(dir_path+"\\"+i)
print(list3)  

I am getting output as :

["C:\\Users\\Desktop\\ABC\\001.py", "C:\\Users\\Desktop\\ABC\\001.xls", "C:\\Users\\Desktop\\ABC\\001.pdf"]

I am looking for output as :

["C:\Users\Desktop\ABC\001.py", "C:\Users\Desktop\ABC\001.xls", "C:\Users\Desktop\ABC\001.pdf"]
Anuj
  • 119
  • 8
  • 1
    This is just how strings with backslashes are represented. Instead of `print(list3)`, try `for x in list3: print(x)` – tobias_k Sep 09 '20 at 14:58

1 Answers1

1

If you can use Python 3, pathlib can help you assemble your paths in a clearer way! If you're forced to use Python 2, you could bring in the library it's based off!

The double-backslash occurs and needs to be dealt with because Windows bizarrely chose to use \ instead of / as the path separator while it is ubiquitous as an escape character in many, especially C-derived languages. You can use / and it'll still work fine. You'll find need to escape spaces with \ when not using pathlib too.

ti7
  • 16,375
  • 6
  • 40
  • 68
  • I got this. suppose i need to open some file with path like "C:\\User\\ABC\\abc.txt" will it open using Python script ?? – Anuj Sep 09 '20 at 15:14
  • @Anuj Practically, it's the difference between how strings are written, displayed, and stored. In order to represent some characters (such as the newline char `\n` or \\) when *building* a string, they are prefixed by \. They're stored as bytes with an associated encoding (such as `utf-8`). Then when printing, *some* representations will show the escape chars, and others will not, ideally depending on what's most practical, but not always (this is often much more obvious with newlines). – ti7 Sep 09 '20 at 15:27
  • Apparently this also affects the SO comment system, so it's quite difficult to show single backslashes in a consistent way here. – ti7 Sep 09 '20 at 15:31