2015-01-15 148 views
-2

所以基本上我试图制作一个程序,以格式“Smith,Robert” 格式的文件命名,并输出看起来像“RobeSmit,Smith,Robert,RobertSmith,(随机生成的密码)”的输出。我拥有这一切工作,但它只能做一个名字,我需要的,因为在该文件,例如它做尽可能多的:史密斯,罗伯特 京东方,乔如何在python中将文件拆分为单独的行?

以下是我有:

import random 

def readFile(): 
    f_input = open("myFile.txt", "r") 
    string = f_input.read() 
    f_input.close 
    return string 

def firstFour(string): 
    lastNameFour, firstNameFour = string.split(",") 
    userName = (str(firstNameFour[1:5]) + str(lastNameFour[0:4])) 
    return userName 

def nameArrangement(string): 
    lastName, firstName = string.split(",") 
    names = (str(lastName)) + "," + str(firstName) + "," + str(firstName) + str(lastName) 
    return names 

def passwordGen(): 
    alphabet = "[email protected]#$%^&*()-=_+\][|}{;?/.,<>" 
    length = 7 
    password = " " 
    for i in range (length): 
     nextChr = random.randrange(len(alphabet)) 
     password = password + alphabet[nextChr] 
    return password 

def putItTogether(userName, names, password): 
    output = userName + ", " + names + ", " + password 
    print (output) 

def main(): 
    string = readFile() 
    userName = firstFour(string) 
    names = nameArrangement(string) 
    character = passwordGen() 
    putItTogether(userName, names, character) 

if __name__ == '__main__': 
    main()` 

任何帮助,将不胜感激。谢谢!

+0

你能详细说明你有什么问题吗?从文件中读取?解析文件中的数据? – ryanyuyu 2015-01-15 16:22:09

+0

查看readlines()的文档。或者,尝试在readFile方法之外打开文件。然后,每次调用readFile都会返回文件的下一行。您只需检查文件结尾即可。用于将文件拆分为行的 – user1245262 2015-01-15 16:25:03

+0

试试这个:f.readlines()。 – 2015-01-15 16:26:18

回答

0

让我们看一下你的代码,并嵌入读线到它。

变化readFile返回所有行:

def readFile(): 
    # with is used when a resource is only needed in a certain context. 
    # we'll use it for opening files so they close automatically. 
    with open("myFile.txt", "r") as f: 
     return f.readlines() 

saveFile到在文件中存储处理的行:

def writefile(lines): 
    with open("myFile.txt", "w") as f: 
     f.writelines(lines) 

收件processLine包裹单个行的处理和返回结果 (不需要putItTogether):

def processLine(line): 
    userName = firstFour(string) 
    names = nameArrangement(string) 
    character = passwordGen() 
    return userName + ", " + names + ", " + password 

现在申请的处理使用map(可以做list comprehension以及)所有线路,并把它们写回:

def main() 
    writeFile(map(processLine, readFile())) 

提示:这不是很一般,想想办法,以抽象的行动从价值观。例如readFile应该读取一个文件,而不是一个特定的文件。它应该被定义为def readFile(filename)

祝你好运。

0

main功能是对子级:

def main(): 
    with open("myFile.txt", "r") as f: 
     for string in f: 
      userName = firstFour(string) 
      names = nameArrangement(string) 
      character = passwordGen() 
      putItTogether(userName, names, character) 
相关问题