elesis's haunt

[Python] SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape 본문

프로그래밍 언어/Python

[Python] SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

elesis 2022. 3. 13. 21:51
import os

# 파일탐색기에서 복사한 형태에서, \U 부분이 유니코드로 인식되어 해당 에러가 납니다.
path = "C:\Users\유저이름\Downloads"                            -----(X)
path = "C:/Users/유저이름/Downloads"                            -----(O)

# os에서 login중인 유저이름을 받아오고 싶을 때
# 동일한 방식의 두 코드 ( {}에 유저이름이 들어갑니다. )
path = "C:\\Users\\{}\\desktop".format(os.getlogin())          -----(O) # \\방식
path = r"C:\Users\{}\Downloads".format(os.getlogin())          -----(O) # r방식

# 리스트로 삽입하고 싶을 때
list_path = ["C:/Users/", os.getlogin() +"/Downloads"]
path = os.path.join(*list_path)


print(path) # C:\\Users\\유저이름\\Downloads
Comments