Escape space in the file path

I am trying to write a python tool that will read a log file and process it

One thing he should do is use the paths listed in the log file (this is the log file for the backup tool)

/Volumes/Live_Jobs/Live_Jobs/*SCANS\ and\ LE\ Docs/_LE_PROOFS_DOCS/JEM_lj/JEM/0002_OXO_CorkScrew/3\ Delivery/GG_Double\ Lever\ Waiters\ Corkscrew_072613_Mike_RETOUCHED/gg_3110200_2_V3_Final.tif 

Unfortunately, the paths that were provided to me were not properly escaped, and I was having trouble escalating in python. Python may not be the best tool for this, but I like the flexibility - it will allow me to extend everything I write

Using the regex escape expression function speeds up too many characters, the pipe.quote method does not remove spaces, and if I use a regular expression to replace '' with '\', I get

 /Volumes/Live_Jobs/Live_Jobs/*SCANS\\ and\\ LE\\ Docs/_LE_PROOFS_DOCS/JEM_lj/JEM/0002_OXO_CorkScrew/3\\ Delivery/GG_Double\\ Lever\\ Waiters\\ Corkscrew_072613_Mike_RETOUCHED/gg_3110200_2_V3_Final.tif 

which are double escaped and not passed in python functions like os.path.getsize() .

What am I doing wrong?

+4
source share
2 answers

If you read paths from a file and pass them to functions like os.path.getsize , you do not need to avoid them. For instance:

 >>> with open('name with spaces', 'w') as f: ... f.write('abc\n') >>> os.path.getsize('name with spaces') 4 

In fact, in Python there are only a few functions that need spaces because they pass the string to the shell (like os.system ) or because they try to parse your name differently (like subprocess.foo using a string arg instead of arg list).


So let logfile.txt look like this:

 /Volumes/My Drive/My Scans/Batch 1/foo bar.tif /Volumes/My Drive/My Scans/Batch 1/spam eggs.tif /Volumes/My Drive/My Scans/Batch 2/another long name.tif 

... then something like this will work fine:

 with open('logfile.txt') as logf: for line in logf: with open(line.rstrip()) as f: do_something_with_tiff_file(f) 

Noticing those * characters in your example, if these are glob patterns, this is good too:

 with open('logfile.txt') as logf: for line in logf: for path in glob.glob(line.rstrip()): with open(path) as f: do_something_with_tiff_file(f) 

If your problem is completely opposite to what you described, and the file is filled with lines that are escaped and you want to cancel them, decode('string_escape') cancels the erasure in the Python style, and there are different functions for undoing different types of escaping, but without knowing which the kind of escape you want to cancel, it's hard to say which function you want ...

+6
source

Try the following:

  myfile = open(r'c:\tmp\junkpythonfile','w') 

"r" stands for raw string.

You can also use \ like

 myfile = open('c:\\tmp\\junkpythonfile','w') 
+1
source

Source: https://habr.com/ru/post/1496051/


All Articles