5

Given is a variable that contains a windows file path. I have to then go and read this file. The problem here is that the path contains escape characters, and I can't seem to get rid of it. I checked os.path and pathlib, but all expect the correct text formatting already, which I can't seem to construct.

For example this. Please note that fPath is given, so I cant prefix it with r for a rawpath.

#this is given, I cant rawpath it with r 
fPath = "P:\python\t\temp.txt"

file = open(fPath, "r")
for line in file:
    print (line)

How can I turn fPath via some function or method from:

"P:\python\t\temp.txt"

to

"P:/python/t/temp.txt"

I've tried also tried .replace("\","/"), which doesnt work.

I'm using Python 3.7 for this.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
RedBoxes
  • 81
  • 1
  • 1
  • 6
  • "P:\python\t\temp.txt".replace("\\", "/") works fine for me! – Fourier Oct 01 '18 at 14:37
  • I used replace("\\\","/"). It even is escaped when writing here. – RedBoxes Oct 01 '18 at 14:37
  • @Fourier, for me it doesn't. This is what I get: `OSError: [Errno 22] Invalid argument: 'P:/python\t\temp.txt'` – RedBoxes Oct 01 '18 at 14:45
  • could you paste the path from properties of the temp.txt – Albin Paul Oct 01 '18 at 14:46
  • @AlbinPaul If I understood what you are asking: The properties window for the file lists this `Location: P:\python\t` – RedBoxes Oct 01 '18 at 14:54
  • Does this answer your question? [How to change the format of a path string to a different OS?](https://stackoverflow.com/questions/11888943/how-to-change-the-format-of-a-path-string-to-a-different-os) – Tomerikoo Apr 26 '21 at 11:59

7 Answers7

9

You can use os.path.abspath() to convert it:

print(os.path.abspath("P:\python\t\temp.txt"))

>>> P:/python/t/temp.txt

See the documentation of os.path here.

Nordle
  • 2,915
  • 3
  • 16
  • 34
  • `OSError: [Errno 22] Invalid argument: 'P:\\python\t\temp.txt'` No luck. This is the error I get. :/ – RedBoxes Oct 01 '18 at 14:40
  • Ah, where does the string come from? – Nordle Oct 01 '18 at 14:44
  • From a different .txt containing windows filepaths. It functions as a job list that I work through. For the problem at hand here, this file is uneditable and cannot be altered. I recieve windows style file paths and have to deal with it. Modifiyng the source is not possible. – RedBoxes Oct 01 '18 at 14:48
3

I've solved it.

The issues lies with the python interpreter. \t and all the others don't exist as such data, but are interpretations of nonprint characters.

So I got a bit lucky and someone else already faced the same problem and solved it with a hard brute-force method:

http://code.activestate.com/recipes/65211/

I just had to find it.

After that I have a raw string without escaped characters, and just need to run the simple replace() on it to get a workable path.

RedBoxes
  • 81
  • 1
  • 1
  • 6
2

You can use Path function from pathlib library.

from pathlib import Path

docs_folder = Path("some_folder/some_folder/")
text_file = docs_folder / "some_file.txt"
f = open(text_file)
Adriano Silva
  • 2,518
  • 1
  • 17
  • 29
  • This requires the path of the correct format already. I tried this: `docs_folder = Path("P:\python\t\temp.txt") f = open(docs_folder) for line in f: print (line)` And got this: `OSError: [Errno 22] Invalid argument: 'P:\\python\t\temp.txt'` – RedBoxes Oct 01 '18 at 14:51
  • Use Path(r'P:\python\t\temp.txt') instead it. – Adriano Silva Oct 01 '18 at 14:57
  • I specifically mentioned this case in the original question. I have no control over the path origin. I am given a variable with a windows style path. Nothing I can change about that. The source data has to be in this style of format. – RedBoxes Oct 01 '18 at 14:59
  • See the PureWindowsPath function: https://docs.python.org/3/library/pathlib.html#pathlib.PureWindowsPath – Adriano Silva Oct 01 '18 at 15:03
  • None of these work with windows paths. They all expect fwd-slashes as input. – RedBoxes Oct 01 '18 at 15:13
1

if you would like to do replace then do

replace("\\","/")

tbalaz
  • 159
  • 3
1

When using python version >= 3.4, the class Path from module pathlib offers a function called as_posix, which will sort of convert a path to *nix style path. For example, if you were to build Path object via p = pathlib.Path('C:\\Windows\\SysWOW64\\regedit.exe'), asking it for p.as_posix() it would yield C:/Windows/SysWOW64/regedit.exe. So to obtain a complete *nix style path, you'd need to convert the drive letter manually.

blurryroots
  • 402
  • 5
  • 12
1

I came across similar problem with Windows file paths. This is what is working for me:

    import os
    file = input(str().split('\\')
    file = '/'.join(file)

This gave me the input from this:

    "D:\test.txt"

to this:

    "D:/test.txt"

Basically when trying to work with the Windows path, python tends to replace '' to '\'. It goes for every backslash. When working with filepaths, you won't have double slashes since those are splitting folder names. This way you can list all folders by order by splitting '\' and then rejoining them by .join function with frontslash.

Hopefully this helps!

Isoide
  • 11
  • 2
0

Use below function, this will pass most of the cases

def resolve_path(path):
   parent_replace=['\t','\n','\r','\f','\v','\a','\b','\000','\\']
   child_replace=['/t','/n','/r','/f','/v','/a','/b','/000','/']
   for i in range(len(parent_replace)):
      path=path.replace(parent_replace[i],child_replace[i])
   return path