-1

My code is supposed to create .csv files and it does, but it doesn't always append the .csv extension to the end of the file even though it is a .csv. I just want to check the final output file before it is returned to the user, and append .csv if it doesn't have that extension.

Here is the snippet I'm using currently:

if not path_to_file.endswith('.csv' or '.json'):
    path_to_file.append('.csv')
else:
    return path_to_file.absolute()

This throws an error: AttributeError: 'PosixPath' object has no attribute 'endswith'.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

1

Working with paths calls for using pathlib. You don't even need to check for the current extension and simply use the with_suffix() method:

from pathlib import Path

print(Path("/a/b/c").with_suffix(".csv"))
print(Path("/a/b/c.csv").with_suffix(".csv"))

Will both give:

\a\b\c.csv
\a\b\c.csv
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61