嘿傢伙我是新來的蟒蛇我在11年,所以我仍然在學習我寫了一個代碼,循環詢問什麼useres名稱是他們的年齡和年份組的問題,然後打印出一個用戶名,其中包含他們名字的前3個字母和年齡組,然後年齡? 我想知道如何將所有這些用戶名寫入文件我使用for循環重複5次問題以詢問5個不同的用戶,現在我想知道如何將他們的用戶名存儲到文件中我知道如何存儲輸入但不包含此類問題寫一個循環到一個文件
-3
A
回答
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
相關問題
- 1. shell循環寫入同一個文件
- 2. C++在一個循環內寫入一個文件
- 3. 在一個類中循環並寫入一個txt文件
- 4. 從一個循環我寫
- 5. 寫一個並行循環
- 6. 如何寫一個循環
- 7. 用JQUERY寫一個循環
- 8. 在一個循環中寫入多個CSV文件
- 9. 爲什麼不把這個循環寫入每個元素到一個文件?
- 10. C#寫入一個「到一個文件
- 11. 寫一個數組到一個文件
- 12. 麻煩寫一個If-else條件的一個循環在wordpress
- 13. 寫一個存在的條件,打破一個while循環
- 14. 如何退出一個循環到另一個循環?
- 15. 寫一個NSArray到文件
- 16. 找到一個循環
- 17. 變到另一個循環
- 18. 得到一個循環
- 19. CFOUTPUT循環上的一個文件名
- 20. 循環僅刪除第一個文件
- 21. 如何編寫一個循環,直到滿足條件爲止
- 22. 寫在R上的文件使用一個循環
- 23. 試圖輸出,文件撰寫一個for循環從JSON
- 24. 輸出幾個變量到ASCII文件在一個循環中
- 25. 通過循環找到一個值,多個文件python
- 26. 編寫for-each循環,從一個ArrayList
- 27. 用for循環填寫一個列表
- 28. 套接字讀寫一個循環
- 29. 寫一個for循環來創建div
- 30. 編寫一個更好的循環
這感覺就像一個課堂作業。你到目前爲止嘗試了什麼? – mondieki
我已經得到了一切寫入文件除了我有代碼工作,所以它要求用戶的名字年齡和年份組5次,並打印他們的用戶名現在我需要將這些用戶名寫入文件? – OpTiiMiizE
首先你必須打開一個文件hander'output_file = open(「./ usernames.txt」,「w」)''然後用print(「test」,file = output)來代替簡單的'print(username)' )' –