2015-05-14 33 views
0

我在Python中很生鏽(和我的技能,當不生鏽時,最好是基本的),我試圖自動創建配置文件。我基本上試圖獲取MAC地址列表(由用戶手動輸入),並創建以這些MAC地址作爲名稱的文本文件,最後附加.cfg文件。我設法絆倒並接受用戶輸入並將其附加到數組中,但我遇到了一個絆腳石。我明顯處於這個計劃的新生階段,但這是一個開始。下面是我到目前爲止有:用Python中的數組創建新的文本文件

def main(): 
    print('Welcome to the Config Tool!') 
    macTable = [] 
    numOfMACs = int(input('How many MAC addresses are we provisioning today? ')) 
    while len(macTable) < numOfMACs: 
    mac = input("Enter the MAC of the phone: "+".cfg") 
    macTable.append(mac) 


    open(macTable, 'w') 
main() 

可以看出,我試圖把陣列和在打開命令作爲文件名中使用它,和Python不喜歡它。

任何幫助將不勝感激!

+0

你不能使用'打開(macTable,「R」)',因爲'open'需要第一個參數的字符串,而不是列表。你可以在macTable中爲'fname:open(fname,'w')',但是。 – wflynny

回答

1

我能看到的第一個問題是while循環的縮進。您有:

while len(macTable) < numOfMACs: 
mac = input("Enter the MAC of the phone: "+".cfg") 
macTable.append(mac) 

,而應該是:

while len(macTable) < numOfMACs: 
    mac = input("Enter the MAC of the phone: "+".cfg") 
    macTable.append(mac) 

至於文件,你需要在一個循環中打開它們了,所以無論是:

for file in macTable: 
    open(file, 'w') 

或者你可以在此同時也可以這樣做:

while len(macTable) < numOfMACs: 
    mac = input("Enter the MAC of the phone: "+".cfg") 
    macTable.append(mac) 
    open(mac, 'w') 
    macTable.append(mac) 

另一個你可能想要改變的是輸入處理。我明白你想讀取用戶的MAC地址並命名配置文件<MAC>.cfg。因此,我建議改變

mac = input("Enter the MAC of the phone: "+".cfg") 

mac = input("Enter the MAC of the phone:") 
filename = mac + ".cfg" 

,然後你需要決定,如果你想擁有MAC或不會忽略你的文件名macTable

+0

我在while循環中有正確的縮進,格式只是有點棘手,我沒有改正它,而粘貼到我的問題。我在while循環中做了很好的工作!現在插入我的配置! –

+0

有人可以告訴我爲什麼downvote?感謝您讓我知道如何改進我的答案。 – geckon

+0

你不會遞減'numOfMACs'這會導致無限的'while'循環。 – ZdaR

1

您正試圖打開一個列表。你需要像這樣:

open(macTable[index], 'w') 
1

首先你不需要一個單獨的列表來存儲用戶輸入的值,您可以即時創建文件。

def main(): 
    print('Welcome to the Config Tool!') 
    #macTable = [] 
    numOfMACs = int(input('How many MAC addresses are we provisioning today? ')) 
    while numOfMACs: 
     mac = input("Enter the MAC of the phone: ") 
     mac += ".cfg"  # Adding extension to the file name 

     with open(mac, 'w') as dummyFile: # creating a new dummy empty file 
      pass 

     numOfMACs-=1 #Avoiding the infinite loop 
main() 

但是你可以簡單的使用for環路爲指定的次數運行的磨讓你的代碼更加清晰:

def main(): 
     print('Welcome to the Config Tool!') 
     #macTable = [] 
     numOfMACs = int(input('How many MAC addresses are we provisioning today? ')) 
     for i in range(numOfMACs): 
      mac = input("Enter the MAC of the phone: ") 
      mac += ".cfg"  # Adding extension to the file name 

      with open(mac, 'w') as dummyFile: # creating a new dummy empty file 
       pass 
    main() 
相關問題