String for text output and os.remove

This is the place for queries that don't fit in any of the other categories.

String for text output and os.remove

Postby dsclinef » Fri Mar 28, 2014 4:37 pm

Hi,

I've got a short script that takes a string made up of a windows directory and file name and writes it out to a file. I also want to use this string to remove the file if it exists. The error I am running into is I've got a number of \\ in the string so that it prints out as \, but when I use it in the os.remove(), the string retains the \\

Code: Select all
writeFileName = folderLocation + tempOutput + conversion.strip()
os.remove(writeFileName)

When writeFileName is written to a file it looks like:
Code: Select all
c:\temp\Testing_dest\test1\test1 - Copy (2).acd" "c:\temp\Testing_dest\test1\test1 - Copy (2).L5K
When os.remove(writeFileName) errors out it looks like:
Code: Select all
c:\\temp\\Testing_dest\\test1\\test1 - Copy (2).L5K

I understand why these look different, what I am looking for is help getting writeFileName "cleaned up" so that the escape character is removed when I try and delete the file.

I am using Python 3.4, but am happy to change versions if there is a simpler way using 2.6
Last edited by Mekire on Fri Mar 28, 2014 4:40 pm, edited 1 time in total.
Reason: First post lock; code tags.
dsclinef
 
Posts: 1
Joined: Fri Mar 28, 2014 4:21 pm

Re: String for text output and os.remove

Postby rrashkin » Sat Mar 29, 2014 12:17 pm

Try this:

os.remove(writeFileName.replace("\\","/"))
___________________
Bob Rashkin
User avatar
rrashkin
 
Posts: 35
Joined: Tue Feb 12, 2013 4:47 pm

Re: String for text output and os.remove

Postby snippsat » Sat Mar 29, 2014 11:00 pm

so that it prints out as \

Double backslash is the way Python can express a single backslash :?
There is a double backslash even if print() is not showing it.
Code: Select all
s = 'C:\car'
>>> print(s)
C:\car
>>> print(repr(s)) #The truth
'C:\\car'
>>> s
'C:\\car'

So what's the problem with using single \ in a folder name as C:\temp?
Code: Select all
>>> s = 'C:\temp'
>>> s
'C:\temp'
>>> print(s)
C:   emp
>>> print(repr(s))
'C:\temp'

When use print() \t get interpret as it should Horizontal tab
To avoid this always use raw string or double backslash or even / when dealing with filename.
Code: Select all
>>> s = r'C:\temp'
>>> print(s)
C:\temp

>>> print(repr(s)) #The truth
'C:\\temp'

With raw string we are getting correct result C:\temp,that's really is a double backslash behind the scene remember :?
User avatar
snippsat
 
Posts: 132
Joined: Thu Feb 21, 2013 12:04 am


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests