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")