【发布时间】:2021-02-25 13:45:36
【问题描述】:
我的代码应该创建.csv 文件并且确实如此,但它并不总是将.csv 扩展名附加到文件末尾,即使它是.csv。我只想在最终输出文件返回给用户之前检查它,如果没有该扩展名,则附加.csv。
这是我目前使用的 sn-p:
if not path_to_file.endswith('.csv' or '.json'):
path_to_file.append('.csv')
else:
return path_to_file.absolute()
这会引发错误:AttributeError: 'PosixPath' object has no attribute 'endswith'。
【问题讨论】:
-
如果文件名是字符串,可以检查是否以.csv结尾:
if filename.endswith('.csv'):... -
你可以查看 str.endswith() 方法。
-
您是如何保存该文件的?你是如何生成路径的?