我編寫了下面的代碼以檢查三個文件和哪個文件存在,對文件運行「掃描」(如果文件沒有存在,不用擔心它只對可用文件運行「掃描」)並在這些可用文件上生成適當的輸出文件。Python:從一個函數調用變量,但不使用全局變量
我的工作方案包括以下代碼:
def InputScanAnswer():
scan_number = raw_input("Enter Scan Type number: ")
return scan_number
此功能檢查,如果存在這三個文件,如果有的話,指定特定值hashcolumn
和filepathNum
def chkifexists():
list = ['file1.csv', 'file2.csv', 'file3.csv']
for filename in list:
if os.path.isfile(filename):
if filename == "file1.csv":
hashcolumn = 7
filepathNum = 5
if filename == "file2.csv":
hashcolumn = 15
filepathNum = 5
if filename == "file3.csv":
hashcolumn = 1
filepathNum = 0
#print filename, hashcolumn, filepathNum
def ScanChoice(scan_number):
if scan_number == "1":
chkifexists()
onlinescan(filename, filename + "_Online_Scan_Results.csv", hashcolumn, filepathNum) #this is what is giving me errors...
elif scan_number == "2":
print "this is scan #2"
elif scan_number =="3":
print "this is scan #3"
else:
print "Oops! Invalid selection. Please try again."
def onlinescan(FileToScan, ResultsFile, hashcolumn, filepathNum):
# web scraping stuff is done in this function
我遇到的錯誤是global name 'filename' is not defined
。 我意識到問題是我試圖將本地變量從chkifexists()
發送到onlinescan()
參數。我嘗試使用
return filename
return hashcolumn
return filepathNum
在chkifexists()
功能的結尾,但那也不起作用。反正有做什麼我想在
onlinescan(filename, filename + "_Online_Scan_Results.csv", hashcolumn, filepathNum)
線做不使用全局變量?我知道他們很沮喪,我希望我能以另一種方式去做。另外,是否有hashcolumn
和filepathNum
參數onlinescan()
與此有什麼關係?
謝謝,這個工作就像我希望的一樣! – serk
訂單怎麼樣?它也可以是這樣的:'chkifexists()= filename,hashcolumn,filepathNum'? – serk
這很容易在你的解釋器中嘗試,但由於我感覺很慷慨,我會給你答案:不,你得到一個'SyntaxError:不能分配給函數調用。其中,當你考慮一個secoond時,這很有意義。 – Nate