我在涉及打開文本檔案的任何 python 腳本中都遇到了這個問題。我已經嘗試過各種 IDE,包括 VSCode 和 PyCharm,并且一切都按預期作業。但是,一旦我真正運行 python 腳本,它就會關閉(由于打開外部檔案時出錯,正如通過注釋掉代碼的各個部分所發現的那樣)。
這是一個非常簡單的腳本,它在 IDE 中運行良好,但在實際打開 python 檔案時卻不能:
主要.py:
print("This is a demo of the problem.")
file = open("demofile.txt", "r") #this line causes an error outside of IDE
print(file.readlines())
file.close()
演示檔案.txt:
this is line 1
this is line 2
this is line 3
這兩個檔案都存盤在 Desktop 的同一個檔案夾中,但是當我將代碼修改為:
import os
try:
file = open("demofile.txt", "r")
file.close()
except:
print(os.path.abspath("demofile.txt"))
print(os.path.abspath("main.py"))
我得到了一個意想不到的輸出:
C:\WINDOWS\system32\demofile.txt
C:\WINDOWS\system32\main.py
任何幫助,將不勝感激。
uj5u.com熱心網友回復:
處理輸出
C:\WINDOWS\system32\demofile.txt
C:\WINDOWS\system32\main.py
從
import os
try:
file = open("demofile.txt", "r")
file.close()
except:
print(os.path.abspath("demofile.txt"))
print(os.path.abspath("main.py"))
輸出不一定意味著檔案存在。
觀察:
>>> import os
>>> os.path.abspath("filethatdoesnotexist.txt")
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python39\\filethatdoesnotexist.txt'
>>>
您要做的是使用以下os.path.exists()方法:
import os
try:
file = open("demofile.txt", "r")
file.close()
except:
print(os.path.exists("demofile.txt"))
print(os.path.exists("main.py"))
所以基本上,當你運行檔案時,Python 以當前路徑的方式作業C:\WINDOWS\system32,因此如果demofile.txt不在那里,你會得到錯誤。
要查看錯誤型別,只需替換
except:
和
except Exception as e:
print(e)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/434588.html
