[英]a question about this python script!
if __name__=="__main__":
fname= raw_input("Please enter your file:")
mTrue=1
Salaries=''
Salarieslist={}
Employeesdept=''
Employeesdeptlist={}
try:
f1=open(fname)
except:
mTrue=0
print 'The %s does not exist!'%fname
if mTrue==1:
ss=[]
for x in f1.readlines():
if 'Salaries' in x:
Salaries=x.strip()
elif 'Employees' in x:
Employeesdept=x.strip()
f1.close()
if Salaries and Employeesdept:
Salaries=Salaries.split('-')[1].strip().split(' ')
for d in Salaries:
s=d.strip().split(':')
Salarieslist[s[0]]=s[1]
Employeesdept=Employeesdept.split('-')[1].strip().split(' ')
for d in Employeesdept:
s=d.strip().split(':')
Employeesdeptlist[s[0]]=s[1]
print "1) what is the average salary in the company: %s "%Salarieslist['Avg']
print "2) what are the maximum and minimum salaries in the company: maximum:%s,minimum:%s "%(Salarieslist['Max'],Salarieslist['Min'])
print "3) How many employees are there in each department :IT:%s, Development:%s, Administration:%s"%(
Employeesdeptlist['IT'],Employeesdeptlist['Development'],Employeesdeptlist['Administration'])
else:
print 'The %s data is err!'%fname
當我輸入文件名但沒有繼續時,為什么? 如果我輸入一個名為company.txt的文件,但它始終顯示該文件不存在。 為什么?
我可以給您一些提示,幫助您更好地解決問題
創建一個函數並在main中調用它,例如
if __name__=="__main__":
main()
if mTrue==1:
整個塊放在下面if mTrue==1:
相反,只要出錯就從函數返回,例如
def main():
fname= raw_input("Please enter your file:")
try:
f1=open(fname)
except:
print 'The %s does not exist!'%fname
return
... # main code here
從不捕獲所有異常,而是捕獲特定異常,例如IOError
try:
f1 = open(fname):
except IOError,e:
print 'The %s does not exist!'%fname
否則捕獲所有異常可能會捕獲語法錯誤或名稱拼寫錯誤等
打印您得到的異常,它可能並不總是找不到文件,可能是您沒有讀取權限或類似的東西
最后您的問題可能只是文件可能不存在,請嘗試輸入完整路徑
您當前的工作目錄不包含company.txt
。 設置當前工作目錄或使用絕對路徑。
您可以像這樣更改工作目錄:
import os
os.chdir(new_path)
除了更具體地了解要捕獲的異常之外,還應考慮捕獲異常對象本身,以便可以將其字符串表示形式輸出為錯誤消息的一部分:
try:
f1 = open(fname, 'r')
except IOError, e:
print >> sys.stderr, "Some error occurred while trying to open %s" % fname
print >> sys.stderr, e
(您還可以了解有關特定類型的Exception對象的更多信息,並可能在代碼中處理某些類型的異常。您甚至可以從解釋器中捕獲異常以供自己檢查,以便可以在它們上運行dir()
和type()
在您發現的每個有趣的屬性上……等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.