2017-08-06 206 views
2

我正在學習Python編程。作爲我的第一次嘗試,我試圖製作一個程序,需要用戶鍵入用戶的數據,然後程序將其存儲。如果可能,請將其寫入.txt文件。如何讀取輸入並將其保存到文件中

我從這開始;

userKey = ["name ","age ","gender "] 
userValue = [input("name "),input("age "),input("gender ")] 
userData = dict(zip(userKey, userValue)) 

但它只能運行一次,所以我嘗試這樣做:

def userData(): 
    userKey = ["name ","age ","gender "] 
    userValue = [input("name "),input("age "),input("gender ")] 
    userData = dict(zip(userKey, userValue)) 

if __name__ == '__main__': 
    print(userData) 

但它不會做我的第一個代碼做了什麼。我怎樣才能讓它繼續下去。

+4

你缺少括號,'print(userData())' –

回答

0

其他解決方案都將無法工作,因爲你必須回報從功能東西。

def userData(): 
    userKey = ["name ","age ","gender "] 
    userValue = [input("name "),input("age "),input("gender ")] 
    data = dict(zip(userKey, userValue)) 
    return data 

如果您希望能夠添加多個用戶,你可以做這樣的事情,使用while循環:

if __name__ == '__main__': 
    ask = True 
    # Get user data 
    userdata = userData() 
    # Write description on first row (table header) 
    with open("user.txt", 'w') as f: 
     for key in userdata.keys(): 
      f.write(key + "\t") 
     f.write("\n") 

    while ask: 
     # Append user data to text file 
     with open("user.txt", 'a') as f: 
      for data in userdata.values(): 
       f.write(data + "\t") 
      f.write("\n") 
     # Ask wheter you want to add a new user and check user input 
     chk = True 
     while chk: 
      add = input("Add another user? [y]/n ") # y is the default answer 
      if not add or add=='y' or add=='yes': 
       chk = False 
       userdata = userData() 
      elif add=='n' or add=='no': 
       ask=False 
       chk = False 
      else: # Prompt again if user entered an invalid string 
       print("Please enter y or n") 

在這裏,我還要檢查有效的輸入,有些東西你還需要做你userData功能,避免用戶提交錯誤值(如字符串多年,無效的性別,或無效的名稱,如包含數字)

+0

我是一個初學編程的人,在這裏堆棧溢出,所以我有點震驚,因爲我得到的答案有多快,這裏是我得到的信息最豐富的答案。它不僅解決了我的問題,而且教會了我一些其他的東西。感謝大衛以及其他回答的人。社區獲勝! –

0
def userData(): 
    userKey = ["name ","age ","gender "] 
    userValue = [input("name "),input("age "),input("gender ")] 
    userData = dict(zip(userKey, userValue)) 

if __name__ == '__main__': 
    print(userData()) 

它現在應該工作。

0

你缺少括號,所以更改此:

print(userData) 

這樣:

print(userData()) 

,你會被罰款。

0

首先,你缺少你的函數調用括號,所以它應該是這樣的:

print(userData()) 

然後,爲了使程序不斷地問用戶輸入您應該使用一個循環要做到這一點:

def userData(): 
    while True: 
     userKey = ["name ","age ","gender "] 
     userValue = [input("name "),input("age "),input("gender ")] 
     userData = dict(zip(userKey, userValue)) 

要停止執行,請按Ctrl+C

然後,爲了編寫成一個文件,使用open()功能在Python:

... 
with open('/path/to/file.txt', 'w') as my_file: 
    my_file.write('data') 
... 
0

我想你可能想這樣做,

def userData(): 
    userKey = ["name ","age ","gender "] 
    userValue = [input("name "),input("age "),input("gender ")] 
    userData = dict(zip(userKey, userValue)) 
    return userData 
if __name__ == '__main__': 
    print(userData()) 
相關問題