Solved

Windows paths break my print — \n in the middle of the path

AmeliaRunsOP

print("C:\new_folder\test.txt") prints a weird line break and a tab. What's going on?

6

Comments 4

Log in to join the discussion.

Log in Create account
  1. CharlieH Solutionreplies: 2

    \n and \t inside a normal string are escape sequences (new line, tab). Your path happens to contain them.

    Options:

    print("C:\\new_folder\\test.txt")   # double backslashes
    print(r"C:\new_folder\test.txt")    # raw string, backslashes kept as they are
    print("C:/new_folder/test.txt")     # forward slashes work on Windows too
    7
    1. AmeliaRunsOP

      Raw string it is. Never knew forward slashes work on Windows!

      2
      1. NoahLoops

        For real projects look at pathlib, it handles separators for you.

        2
      2. FreyaL

        This is the classic Windows trap. Took me a whole evening the first time.

        1