[For beginners] Unexpected behavior if "\" is included when setting the path in Python

Introduction

This article summarizes precautions and remedies when dealing with character strings containing "" backslashes, such as when setting a path in a Windows environment. (On Mac, the path delimiter is a "/" slash, so you don't have to worry about it when setting the path.)

Unexpected behavior if the string contains a "" backslash

For example, when you specify the folder path in the Windows environment as shown below, it may be treated differently from the expected character string.

python


dir_name = 'C:\testDir'
print(dir_name)
#Assumed character string> C:\testDir
#The character string that is actually displayed> C:      estDir

The reason this happens is that the windows path delimiter ** "" backslash is ** used in Python for a process called "escape sequences".

What kind of processing is "escape sequence"? For example, when you want to start a new line in a character string.

python


txt = 'Line break → ← line break here'
# print(txt)I want to display as follows
#Line break here →
#← Line break

Even if you press enter just because you want to insert a line break, a line break will occur on the code and an error will occur.

python


txt = 'Line break here →
← Line break'
# SyntaxError: EOL while scanning string literal

Therefore, the method for representing ** special characters such as "line feed" is "escape sequence" **. The character that means a line break is represented by'\ n', which is a combination of the backslash'\ 'and'n'.

python


txt = 'Line break here →\n ← line break'
print(txt)
#↓ Displayed character string
#Line break here →
#← Line break

In the example of setting the first path, the \ t part of dir_name ='C: \ testDir' is treated as the character " TAB ". It was recognized as 'C: [TAB] estDir' by Python, and it was an unnaturally empty character string.

approach

Therefore, there is a way to treat "" as a character string "" backslash as it is instead of "" for escape sequences.

Method 1: raw string

At the beginning of the string, add the acronym "r" for "raw" which means "as is". It is called a raw string, and it will be treated as it is without escaping.

python


#If r is added, it will be treated as a string as it is and will not be escaped.
r'C:\testDir'

#However, at the end, "\Cannot be supported if it contains ""
r'C:\testDir\'
# SyntaxError: EOL while scanning string literal

Method 2: Escape the "" backslash

Since "" is also a special character, it can be expressed by an escape sequence as "this is a backslash". If you write two backslashes "\\", they will be treated as backslashes.

python


#Two backslashes "\\Write to escape the backslash itself
'C:\\testDir'

Method 3: Replace the "" backslash with a "/" slash

I think this method is the best for the path. Since the delimiter character of the path of Linux and Mac is a "/" slash, if you are conscious of unifying it with "/", you can prevent problems when you change the environment.

Because Windows can also support with the delimiter "/" slash Rewrite the "" backslash with a "/" slash to deal with it.

python


# 「\"Backslash"/Rewrite to slash
'C:/testDir'

important point

As a precaution when rewriting backslashes to slashes When using the function to get the path, the path delimiter is "" backslash.

The following is running on'C: \ testDir'.

python


import os
#Get current directory(Working folder)
current_dir = os.getcwd()
print(current_dir)
# C:\testDir 「\Get with a backslash

If you use this acquired path and set the subsequent paths yourself, you need to be careful not to mix "/" and "".

python


import os
#Get current directory
current_dir = os.getcwd()
#Set a folder for images "/Write the continuation path with
image_dir = f'{current_dir}/image'
print(image_dir)
# C:\testDir/image 「\」「/"Mixed

In the python function, it works even if it is mixed, but when passing the path to another system or manipulating the path as a string, an error occurs. Example) When setting the download folder of Chrome in Selenium

Therefore, as a workaround, replace "" with "/" when getting the path, and then get it.

python


import os
#When getting the current directory, set the delimiter to "/Replaced with
current_dir = os.getcwd().replace(os.sep,'/')
print(current_dir)
# C:/testDir

in conclusion

Thank you for visiting. There are various ways to deal with the "" backslash, but let's set rules on site or by ourselves and unify them so that we can develop without problems.

reference

Use escape sequences Raw string that ignores (disables) escape sequences in Python Get Separator

Recommended Posts

[For beginners] Unexpected behavior if "\" is included when setting the path in Python
Check if the string is a number in python
When reading an image with SimpleITK, there is a problem if there is Japanese in the path
Check the behavior when assigning Python
Behavior when listing in Python heapq
Get the desktop path in Python
Get the script path in Python
Get the desktop path in Python
What is the python underscore (_) for?
Run unittests in Python (for beginners)
Behavior when 0, 1, False, True is used for the dictionary (dict) key
[Golang] Check if a specific character string is included in the character string
What to do when the value type is ambiguous in Python?
Check the behavior of destructor in Python
Behavior when returning in the with block
Inject is recommended for DDD in Python
[python, multiprocessing] Behavior for exceptions when using multiprocessing
[Example of Python improvement] What is the recommended learning site for Python beginners?
Check if the URL exists in Python
What is "mahjong" in the Python library? ??
When the target is Ubuntu 16.04 in Ansible
MongoDB for the first time in Python
Notify using Notification Center when the execution environment is macOS in Python
A useful note when using Python for the first time in a while
Even if the development language is changed to python3 in Cloud9, version 2 is displayed in python --version
Notify using Notification Center when the execution environment is macOS in Python
Differences in the behavior of each LL language when the list index is skipped
CERTIFICATE_VERIFY_FAILED in Python 3.6, the official installer for macOS
The fastest way for beginners to master Python
Check if the characters are similar in Python
What is wheezy in the Docker Python image?
About the difference between "==" and "is" in python
Tips for hitting the ATND API in Python
Try to calculate RPN in Python (for beginners)
About the behavior of Model.get_or_create () of peewee in Python
Behavior when saving python datetime object in MongoDB
[Introduction for beginners] Working with MySQL in Python
Basic story of inheritance in Python (for beginners)
Libraries that should be included when creating APIs in the Django Rest Frakework environment, vscode extensions, etc. (for beginners)
Python --If statement judgment behavior under multiple conditions (even though the order is different)
Import audit.log into Splunk and check the behavior when Splunk is started for the first time
What to do if the progress bar is not displayed in tqdm of python
How to check in Python if one of the elements of a list is in another list
[For beginners] Web scraping with Python "Access the URL in the page to get the contents"
Things to keep in mind when building automation tools for the manufacturing floor in Python
[Python] Precautions when it does not work even if TimedRotatingFileHandler is set in basicConfig in python2
[Introduction to Python] What is the important "if __name__ =='__main__':" when dealing with modules?
python> Check if code is printable> Use ord () / all (c in string.printable for c in hello)
Rock-paper-scissors poi in Python for beginners (answers and explanations)
[For beginners] How to use say command in python!
Check if it is Unix in the scripting language
Find the part that is 575 from Wikipedia in Python
Embedding in datetime when only the time is known
Electron is the best solution for Python multi-platform development
Determine if an attribute is defined in the object
Python Exercise for Beginners # 1 [Basic Data Types / If Statements]
[For beginners] Learn basic Python grammar for free in 5 hours!
Check if it is Unix in the scripting language
For those who are in trouble because NFC is read infinitely when reading NFC with Python
What to do when there is no response due to Proxy setting in Python web scraping
When converting a string (a-> b) in Python, which is faster, if statement or dictionary type?