正如您在下面看到的那样,我正在尝试制作一个程序,该程序接收一个名为names.txt的文件,并使用.split('/ n')将其分解为一个列表,然后为列表中的每个用户添加一个密码。由于某种原因,for外观将列表视为字符串,因此不要将其视为:
鲍勃 查理 罗恩
它像下面这样分解:
B Ø b
C H .... 因此,给每个字母一个密码而不是列表本身。
我在做什么错? 有没有一种方法可以测试以查看实际上给出了for循环?
我一直在使用它来查看是否给了它一个字符串,但是在打印时该列表似乎只是一个列表,所以为什么在for循环中将其视为字符串?
def importNames():
try:
file = open("names.txt", "r")
contents = file.read()
print(contents)
file.close()
return contents
except:
print("The file was not found.")
print("Make sure you have a file called \"names.txt\" in the working directory (where you ran this program)")
exit()
def createPasswordList(nameList):
print("They are being given the standard password of \"p@ssw0rd.\"")
#nameList = ["Pickles", "Bob's", 'wow zers john'] #This is for testing purposes. It works just fine, but the original nameList breaks down badly.
passList = []
#for x, value in enumerate(nameList):
for i in nameList:
print(i)
passList.append("p@ssw0rd")
print(passList)
return passList
def createUsers(nameList, passwordList): #takes in a list of usernames, then adds creates them.
for i in nameList:
print("This will do something soon.")
#encPass = crypt.crypt(passwordList[i],"22") #22 is a salt number, use crypt per useradd manual
#os.system("useradd -p " + encPass + " " + nameList[i]) #useradd -p encryptedpass username
def convertNamesToList(originalList):
print("Converting names.") #Use newline as a delimiter
newList = originalList.split('\n')
print(newList)
return newList
def convertNameToUsernames(originalNames):
print("Creating usernames")
print("This program is used to make some users.")
print("If you import a file, have it in the working directory called \"names.txt\".")
print("Would you like to import names or add them manually? (n/m)")
answer = input()
if (answer is 'm' or answer is 'M'):
createUser()
print("The user gets created. Good job.")
else:
originalNames = importNames() #this will return a string of the file.
convertNamesToList(originalNames) #convert the string to sets of names. Use newlines as delimiters.
#convert the names to usernames
print("Do the users have passwords? (y/n)")
#answer = input()
answer = 'n' ###FORCE###
if (answer is 'n' or answer is 'N'):
passwordList = createPasswordList(originalNames)
答案 0 :(得分:2)
对于convertNamesToList
的返回值,您永远不会做任何事情。您不会将其存储在任何地方。然后,您将originalNames
(它是一个字符串(甚至在注释中指出))传递给createPasswordList
。
我认为您想要类似的东西
originalNames = importNames() #this will return a string of the file.
listOfNames = convertNamesToList(originalNames) #convert the string to sets of names. Use newlines as delimiters.
#convert the names to usernames
print("Do the users have passwords? (y/n)")
#answer = input()
answer = 'n' ###FORCE###
if (answer is 'n' or answer is 'N'):
passwordList = createPasswordList(listOfNames)
答案 1 :(得分:0)
看起来您的nameList实际上是一个字符串。假设您在names.txt文件的每一行都有一个名称,请尝试以下操作:
def importNames():
try:
file = open("names.txt", "r")
contents=[]
for line in file.read():
contents.append(line)
print(contents)
file.close()
return contents
那么您以后就不需要将其转换为列表。