Ad

Get R"D:\test.txt" Or "D:\\test.txt" From Glob.glob("D\\*.txt")

- 1 answer

I want to get r"D:\test.txt" or "D:\\test.txt" from glob.glob list.

I tried as follows.

files = glob.glob("D\\*.txt")
for fi in files:
  print (fi)

It just gives, "D\test.txt".

How to make it r"D:\test.txt" or "D:\\test.txt"

  • fi is given condition.
  • I need to get it as string (r"D:\test.txt" or "D:\\test.txt").
    • I also tried as print (str(fi).replace("\", "\\")) but python does not allow writing this code.
  • I am using windows.
Ad

Answer

you have fi as "D:\test.txt" if that is a string you replace function to convert \ into \

fi = fi.replace("\\","\\\\")

First \ is for escape second \ is for search in the fi string in the four \, 2 for escape and 2 for your string.

Ad
source: stackoverflow.com
Ad