- 1、在Terminal中用python創建目錄,顯示語法錯誤
- 2、python如何自定義異常?
- 3、為什麼python創建文件失敗
- 4、python創建對象時出現錯誤………..
- 5、python 字典創建問題?
- 6、jupyter 創建新的python3 時,出現錯誤:Permission denied: Untitled.ipynb
Terminal指的是終端,並不是python里的IDE shell,而是電腦中命令提示符,打開進入你要創建目錄所在盤符,然後再使用mkdir來創建一個目錄就可以了
8.5. 用戶自定義異常
在程序中可以通過創建新的異常類型來命名自己的異常(Python 類的內容請參見 類 )。異常類通常應該直接或間接的從 Exception 類派生,例如:
class MyError(Exception):
… def __init__(self, value):
… self.value = value
… def __str__(self):
… return repr(self.value)
…
try:
… raise MyError(2*2)
… except MyError as e:
… print(‘My exception occurred, value:’, e.value)
…
My exception occurred, value: 4
raise MyError(‘oops!’)
Traceback (most recent call last):
File “
“, line 1, in ?
__main__.MyError: ‘oops!’
在這個例子中,Exception 默認的 __init__() 被覆蓋。新的方式簡單的創建 value 屬性。這就替換了原來創建 args 屬性的方式。
異常類中可以定義任何其它類中可以定義的東西,但是通常為了保持簡單,只在其中加入幾個屬性信息,以供異常處理句柄提取。如果一個新創建的模塊中需要拋出幾種不同的錯誤時,一個通常的作法是為該模塊定義一個異常基類,然後針對不同的錯誤類型派生出對應的異常子類:
class Error(Exception):
“””Base class for exceptions in this module.”””
pass
class InputError(Error):
“””Exception raised for errors in the input.
Attributes:
expression — input expression in which the error occurred
message — explanation of the error
“””
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
“””Raised when an operation attempts a state transition that’s not
allowed.
Attributes:
previous — state at beginning of transition
next — attempted new state
message — explanation of why the specific transition is not allowed
“””
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
與標準異常相似,大多數異常的命名都以 「Error」 結尾。
很多標準模塊中都定義了自己的異常,用以報告在他們所定義的函數中可能發生的錯誤。
Python中有幾個內置模塊和方法來處理文件。這些方法被分割到例如os, os.path , shutil 和 pathlib 等等幾個模塊中。
推薦:Python教程
創建好的Python文件打不開的話,可以嘗試用記事本打開,或者其他的編輯器,嘗試用Sublime text打開試試看。
另外,再檢查一下,文件的名字確定是.py還是.py.txt,把後綴名要理清楚了,Python文件的默認後綴名是.py,如果文件格式不對,同
樣是打不開文件的。
更多技術請關注Python視頻教程。
這個類沒有初始化方法,給個字典做參數不知道怎麼處理
在類的頭部加上初始化方法
def __init__(self,items={}):
“””Optionally pass in an inital dictionary of items”””
if type(items)!=type({}):
raise TypeError(“Fridge requires a dictionary but was given %s”%type(items))
self.items=items
python創建文件與文件夾1.文件的創建:一般創建.txt文件函數open(file,’mode’)file為文件地址,若不存在則新建,若不再本目錄下,可以寫絕對路徑mode有以下幾種方式:r只讀 rb二進制只讀 w寫入且原有內容覆蓋 a在文件末尾追加打開後文件需要.close()關閉2.文件夾的創建:使用os.mkdir(ad)方式建立,ad為新建文件夾名稱的絕對路徑
瀏覽器打開jupyter後,出現一堆文件,然後點擊new創建新的python文件時,跳出錯誤:Permission denied: Untitled.ipynb。
解決方式如下:
cmd輸入jupyter notebook –generate-config,可以看到jupyter_notebook_config.py文件的地址,修改一下jupyter_notebook的保存路徑。具體操作方式:打開jupyter_notebook_config.py文件,找到 #c.NotebookApp.notebook_dir = ” ,將這句話改為:c.NotebookApp.notebook_dir = ‘你想保存的路徑’ 。例如:c.NotebookApp.notebook_dir = ‘F:/JupyterProject’。 也就是去掉注釋符號#號,然後在單引號里加上路徑。
原創文章,作者:CBQ7I,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/126122.html