【问题标题】:Is there a way to check if a file has an extension, and if not append that extension?有没有办法检查文件是否有扩展名,如果没有附加该扩展名?
【发布时间】: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() 方法。
  • 您是如何保存该文件的?你是如何生成路径的?

标签: python path pathlib


【解决方案1】:

使用路径需要使用pathlib。您甚至不需要检查当前的扩展名,只需使用with_suffix() 方法:

from pathlib import Path

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

都会给:

\a\b\c.csv
\a\b\c.csv

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-07
    • 2012-12-24
    • 2019-07-07
    • 2019-05-20
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2016-06-28
    相关资源
    最近更新 更多