简体   繁体   中英

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

When I am using (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;

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. 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 ). This is because the REPL calls repr(your_string) before printing it out so that the string can fit into one line.

In your case, \\f and \\t are actually mistakes:

>>> 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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