简体   繁体   English

使用时,Python将反斜杠加倍; 使用open(C:\\ directory_name)作为file_object(PyCharm IDE)

[英]Python doubling backslashes when using; with open(C:\directory_name) as file_object (PyCharm IDE)

When I am using (PyCharm IDE): 当我使用(PyCharm IDE)时:

with open("C:\file_path\target_file") as path_object:

It always doubles the the drive backslash. 它总是使驱动器反斜杠加倍。

I've tried input the path using a raw string, same result; 我尝试使用原始字符串输入路径,结果相同;

file_path = r"C:\file_path\target_file"

and I've tried pathlib/Path, same result; 我尝试过pathlib / Path,结果相同;

from pathlib import Path

file_path = Path("C:\file_path\target_file")

The second backslash comes out as intended but the drive backslash always doubles, no matter what. 第二个反斜杠如预期的那样出现,但是无论如何,驱动器反斜杠总是加倍。 When printing the file path, console shows the path correctly. 打印文件路径时,控制台会正确显示路径。

Also I've tried escaping the backslashes (\\), and it doesn't work. 我也尝试转义反斜杠(\\),但它不起作用。 When searching for the path it prints it as double. 搜索路径时,它会打印为两倍。

You need to distinguish between the string's contents and what the REPL displays. 您需要区分字符串的内容和REPL显示的内容。 For example: 例如:

>>> '''I am a multiline
... string
... '''
'I am a multiline\nstring\n'
>>> print('I am a multiline\nstring\n')
I am a multiline
string

>>>

The two represent the exact same string, even though one contains literal newlines and the other contains newline literals ( \\n ). 即使其中一个包含文字换行符,而另一个包含换行文字( \\n ),两者也表示完全相同的字符串。 This is because the REPL calls repr(your_string) before printing it out so that the string can fit into one line. 这是因为REPL在打印出来之前会调用repr(your_string)以便该字符串适合一行。

In your case, \\f and \\t are actually mistakes: 在您的情况下, \\f\\t实际上是错误:

>>> print("C:\file_path\target_file")
C:
  ile_path  arget_file

This is because \\t represents a tab and \\f represents a form feed, just like \\n represents a newline. 这是因为\\t代表制表符, \\f代表换页,就像\\n代表换行符一样。 The double backslash is actually correct since you want \\ to literally mean a backslash, not the start of an escape sequence: 实际上,双反斜杠是正确的,因为您希望\\字面意思是反斜杠,而不是转义序列的开始:

>>> print("C:\\file_path\\target_file")
C:\file_path\target_file

Using a raw string has the same effect: 使用原始字符串具有相同的效果:

>>> print(r"C:\file_path\target_file")
C:\file_path\target_file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM