开发者

why does using "\" shows error in jython

I am trying to use a copy command for Windows and we have directories such as c:\oracle.

While trying to execute one such, we get the following error:

source_file=folder+"\"
                          ^
SyntaxError: Lexical error at line 17, column 23.  Encountered: "\r" (13), after : ""

Here folder is m开发者_JS百科y path of c:\oracle and while trying to add file to it like:

source=folder+"\"+src_file

I am not able to do so. Any suggestion on how to solve this issue?

I tried with / but my copy windows calling source in os.command is getting "the syntax is incorrect" and the only way to solve it is to use \ but I am getting the above error in doing so.

Please suggest. Thanks for your help

Thanks.


Short answer:

You need:

source_file = folder + "\\" + src_file

Long answer:

The problem with

source_file = folder + "\" + src_file

is that \ is the escape character. What it's doing in this particular case is escaping the " so that it's treated as a character of the string rather than the string terminator, similar to:

source_file = folder + "X + src_file

which would have the same problem.

In other words, you're trying to construct a string consisting of ", some other text and the end of line (\r, the carriage return character). That's where your error is coming from:

Encountered: "\r" (13)


Paxdiablo is absolutely correct about why \ isn't working for you. However, you could also solve your problem by using os.path.normpath instead of trying to construct the proper platform-specific path characters yourself.


In all programming languages I know of, you can't put a quote inside a string like this: "this is a quote: "." The reason for this is that the first quote opens the string, the second then closes it (!), and then the third one opens another string - with the following two problems:

  • whatever is between the quotes #2 and #3 is probably not valid code;
  • the quote #3 is probably not being closed.

There are two common mechanisms of solving this: doubling and escaping. Escaping is far more common, and what it means is you put a special character (usually \) in front of characters that you don't want to be interpreted in their usual value. Thus, "no, *this* is a quote: \"." is a proper string, where the quote #2 is not closing the string - and the character \ does not appear.

However, now you have another problem - how do you actually make the escape character appear in a string? Simple: escape it! "This is an escape: \\!" is how you do it: the backslash #1 is the escape character, and the backslash #2 is the escapee: it will not be interpreted with its usual escape semantics, but as a simple backslash character.

Thus, your line should say this:

source=folder+"\\"+src_file

BTW: upvote for both @paxdiablo (who got in before my diatribe) and @Nick (who has a proper Pythonic way to do what you want to do)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜