os.unlink on Windows
thomas at jollans.com
Sun Aug 8 14:17:26 CEST 2010
On 08/08/2010 01:41 PM, Shambhu wrote:
> Hi Thomas,
> I checked, file is present. Here is my sample script:
> import os
> filename = "C:\SHAMBHU\tmp\text_delete.txt"
> File "C:\SHAMBHU\tmp\text_delete.txt" is accessible but "C:\\SHAMBHU\
> \tmp\\text_delete.txt" is not (with extra backslash in path which is
> added by os.unlink).
os.unlink isn't adding anything. The extra backslashes you're seeing are
being added when DISPLAYING the file name string. That's because Python
uses backslashes to escape special characters in strings.
C:\SHAMBHU mp ext_delete.txt
'\t' is the TAB character.
What is the error message, exactly, when you run the above script? Since
you didn't escape the backslashes properly, I expect it refers to
'C:\\SHAMBHU\tmp\text_delet.txt' -- The first backslash is still a
backslash -- it gets doubled when printed as a string (but NOT when
passed to the OS by unlink), but the second and third ones were used to
create TAB characters. Probably.
Either always double backslashes in paths, or use raw string literals
(r"C:\SHAMBHU\tmp\text_delete.txt" -- keeps the \s) (or use forward
slashes in paths...)
> On Aug 7, 4:46 pm, Thomas Jollans <tho... at jollans.com> wrote:
>> On 08/07/2010 01:10 PM, Shambhu Sharma wrote:
>>> I am new to Python. I was trying to use os.unlink function in
>>> windows. But i am getting error:
>>> OSError: [Errno 2] No such file or directory:
>>> Input file to os.unlink is: 'C:\SHAMBHU\tmp\text_delete.txt'. But
>>> os.unlink is adding extra backslash with pathname.
>> No, it isn't. What you're seeing is simply the repr() of the path name
>>>>> p = r'C:\SHAMBHU\tmp\text_delete.txt'
>> 'C:\\SHAMBHU\\tmp\\text_delete.txt'>>> print(p)
>> I think the file you're trying to delete probably doesn't exist. Why
>> don't you double-check that.
>>> I tried with
>>> Python2.5 and Python3.1 but got same error.
>>> Please suggest how to remove this error.
>>> If linux doesn't have a solution, then u have a wrong problem.
>>> Shambhu Kumar Sharma
>>> 91-98864 91913
More information about the Python-list