2015-01-15 106 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) 
相關問題