2017-10-18 123 views
-3

嘿傢伙我是新來的蟒蛇我在11年,所以我仍然在學習我寫了一個代碼,循環詢問什麼useres名稱是他們的年齡和年份組的問題,然後打印出一個用戶名,其中包含他們名字的前3個字母和年齡組,然後年齡? 我想知道如何將所有這些用戶名寫入文件我使用for循環重複5次問題以詢問5個不同的用戶,現在我想知道如何將他們的用戶名存儲到文件中我知道如何存儲輸入但不包含此類問題寫一個循環到一個文件

+1

這感覺就像一個課堂作業。你到目前爲止嘗試了什麼? – mondieki

+0

我已經得到了一切寫入文件除了我有代碼工作,所以它要求用戶的名字年齡和年份組5次,並打印他們的用戶名現在我需要將這些用戶名寫入文件? – OpTiiMiizE

+0

首先你必須打開一個文件hander'output_file = open(「./ usernames.txt」,「w」)''然後用print(「test」,file = output)來代替簡單的'print(username)' )' –

回答

0

可以通過在寫入模式下打開file對象來將數據保存到Python中的文件。爲此,您可以使用內置的open()函數,該函數返回一個文件對象。 open()函數接受許多可能的參數,但您感興趣的兩個參數是文件名和模式。作爲使用的一個示例:

file = open("your_filename_here.txt", "w") 

這將打開寫入模式名爲your_filename_here.txt一個文件對象,通過使"w"作爲函數的第二個參數表示。從這裏,你可以使用file對象的write()函數把用戶名到本文件:

username = "your_username_here" 
file.write(username + "\n") 

凡在年底\n換行符確保每個用戶名被分配到文本文件中有自己的行。

此函數調用write()函數然後可以放入您的for循環中,以將每個用戶名寫入文件。循環完成後,可以調用file對象的close()函數關閉文件。

file.close() 

從您的程序描述的原型,整個過程會是這個樣子:

# Opens a new or existing file named "usernames.txt". 
file = open("usernames.txt", "w") 

# Assigns the number of users. 
users = 5 

# Loops once for each user. 
for user in range(users): 

    # Collects user's name, year group, and age. 
    name = input("Enter your name:  ") 
    year = input("Enter your year group: ") 
    age = input("Enter your age:  ") 

    # Creates a username for the user. 
    username = name[0:3] + year + age 

    # Prints the username. 
    print("Username: " + username + "\n") 

    # Writes the username to the file. 
    file.write(username + "\n") 

# Closes the file. 
file.close() 
+0

非常感謝大家 – OpTiiMiizE