[英]Python: how can I differentiate between two variables of two different objects of the same class?
[英]How to differentiate between two different type of files in python 2.7?
我有一個工具可以將文件保存為2種格式(一種是JSON,另一種是文本(不帶擴展名)),並具有2個用於打開它們的按鈕。
在工具的升級版本中,我刪除了保存文本格式的操作。 現在我不想要2個按鈕來加載2個不同的文件,我希望兩個文件都用相同的按鈕加載。
因為一個文件具有“ .json”擴展名,而另一個文件沒有任何擴展名,該如何完成。
我知道的一種方法是檢查文件擴展名(這是標准方法嗎?)
還有其他方法嗎?
這樣做的python方式是什么?
是的,您可以只檢查擴展名。 使用endswith
if filename.endswith('.json'):
# it's json
else:
# it's not
或者,您可以檢查文件內容本身。
s = open(filename).read()
try:
json.loads(s)
# it's json
except ValueError:
# it's not
您可以采用兩種方法:
使用os.splitext
確定擴展名是否為'json'
:
if os.splitext(path)[1] == 'json':
...
或嘗試解析為json
,如果失敗json
其他方式解析:
try:
data = json.loads(contents)
except ValueError:
data = parse_text() # your custom function i guess?
import os
if os.path.splitext('file.json')[1] == '.json':
#it's a json file
else:
#it's not a json
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.