2

How do I open and write files using file paths that are cross-compatible with Linux, Mac, and Windows in Python 3?

I made an function that opens an input_file containing the following line, "Hello World." The functions then opens an output_file and writes that line to the output_file. The output file should now have the line, "Hello World."

However, I get a UnicodeError when trying to use the absolute file paths.

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

I tried using os.chdir, os.path, forward slashes for the file paths, double slashes for the file path, and raw strings but none of this worked.

After looking at previous answers to the question Why do I get a SyntaxError for a Unicode escape in my file path?, using os.chdir gives me the error:

NotADirectoryError: [WinError 267] The directory name is invalid

Furthermore, those answers will only work for Windows machines, not Linux or Mac machines.

What should I do to make sure that my function can open any file and write to any file on Linux, Mac, and Windows machines?

    def example_function(input_file_path, output_file_path)
        with open(input_file_path) as input_file:
              with open(output_file_path) as output_file:
                    for line in input_file:
                         output.write(line)

    example_function("C:\Users\Name\InputFolder\TextFolder\input.txt","C:\Users\Name\OutputFolder\DataFolder\output.txt")
  • 1
    Use a package like [`pathlib`](https://docs.python.org/3/library/pathlib.html) – sco1 Feb 09 '18 at 16:31
  • Python has both the `os.path` and the `pathlib` modules to handle paths in cross-platform-friendly ways. Your problem is with using `\U` in a string literal, which is a syntax issue. – Martijn Pieters Feb 09 '18 at 16:41

1 Answers1

2

Always use forward slashes so that you don't accidentally introduce invalid escape sequences such as "\Users".

C:/Users/Name/InputFolder/TextFolder/input.txt
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • As mentioned in my post, "I tried using os.chdir, os.path, forward slashes for the file paths, double slashes for the file path, and raw strings but none of this worked." –  Feb 09 '18 at 18:29
  • You haven't explained how they didn't work. – Ignacio Vazquez-Abrams Feb 09 '18 at 18:30
  • It's generally ok to use forward slashes. However, do not use forward slashes with "\\?\" extended paths. Also, it's best to use backslash when passing paths on the command line, since some programs reserve forward slash for command-line options. – Eryk Sun Feb 09 '18 at 18:37