2015-05-14 32 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() 
相关问题