osdir.com

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

error in os.chdir


On 06/30/18 07:34, Sharan Basappa wrote:
>
> sorry. I mean why my code worked in one case but did not in the other one.
>
> This worked - os.chdir('D:\Projects\Initiatives\machine learning\programs')
>
> This did not work - os.chdir('D:\Projects\Initiatives\machine learning\programs\assertion')
>
> only difference is, I added an additional directory in the problematic case.
>
In Python (and many other languages), certain non-printable characters 
are represented in strings by "escape sequences".? Those escape 
sequences begin with a backslash "\".? In your particular case, there 
are five (possible) escape sequences: "\P", "\I", "\m", "\p", and "\a".? 
All but the last one have no meaning to Python, so they are treated 
literally.? The last one, however, translates to "BEL", or 0x07, which 
is a non-printable code that was once sent to teletypes to ring the 
bell, alerting the operator to an incoming message, or to signal the 
completion of a long-running job.

There are three ways to fix your code.? One is to replace the 
backslashes with forward slashes.? Python will translate them internally 
to the correct path separators for your operating system.

Another way is to replace the backslashes with os.sep, which is a 
portable representation of the native path separator.

A third way is to escape all literal backslashes by doubling them - "\\" 
instead of "\".? However, this will make your code Windows-only (but it 
already is, so that may not matter to you).

-Jim