2014-06-12 23 views
-3

固定代碼;存儲基於計算機的輸入並在命令中更改存儲的輸入

if os.path.isfile(external_file): 
    with open(external_file) as in_f: 
     name = in_f.read() 
else: 
    name = raw_input("What's your name?") 
    with open(external_file, "w") as out_f: 
     out_f.write(name) 

問題是。

它指的是每個使用它的計算機,其名稱以.txt存儲。 我需要爲每個MAC地址/ IP /計算機

我還需要名字不同.TXT從用戶

而且在命令改變,如果沒有名稱爲.txt它不請求名字?

+0

您能否詳細說明您面臨的問題?當代碼作爲聊天機器人在線併爲每個用戶使用一個.txt時,出現問題的意思是什麼,因此會向每個用戶致電其已被告知的第一個名稱。另請注意修復代碼的標識! –

+0

@ user3735393你的代碼中有些東西沒有意義......例如,如果'external_file'不是文件(你可能應該使用'os.path.exists',而不是'os.path.isfile '),你試圖打開它(這可能會失敗,因爲該文件可能不存在),然後什麼都不做('通過')。那有什麼意義呢?你的例子最後還有一個'else'塊,沒有任何相應的'if',我猜測這是一個縮進問題。 – dano

+0

@dano,如果文件不存在,它會失敗嗎? –

回答

0

您可以嘗試這樣做,首先簡單地詢問用戶的名稱,然後檢查文件names.txt是否存在,如果不存在,則創建名稱爲names.txt的新文件並將用戶名添加到它。如果文件存在,現在檢查它是否包含用戶名,如果它包含然後說'Hi + name',否則將名稱追加到文件。

這裏是一個快速和骯髒的修復您的代碼(可以進一步提高!):

import os 
#hard code the path to the external file 
external_file = 'names.txt' 
#Ask the user's name 
name = raw_input("What's your name?") 
#if file exists, use it to load name, else create a new file 
if not os.path.exists(external_file): 
    with open(external_file, "a") as f: # using "a" will append to the file 
     f.write(name) 
     f.write("\n") 
     f.close() 
else: 
    #if file exists, use it to load name, else ask user 
    with open(external_file, "r+") as f:# r+ open a file for reading & writing 
     lines = f.read().split('\n') # split the names 
     #print lines 
     if name in lines: 
      print "Hi {}".format(name) 
     else: 
      f.seek(0,2) # Resolves an issue in Windows 
      f.write(name) 
      f.write("\n") 
      f.close() 

更新:修改的版本檢查僅harcoded名稱:

import os 
#hard code the path to the external file 
external_file = 'names.txt' 
username = 'testuser'# Our hardcoded name 

#if file doesn' exists, create a new file 
if not os.path.exists(external_file): 
    #Ask the user's name 
    name = raw_input("What's your name?") 
    with open(external_file, "a") as f: # using "a" will append to the file 
     f.write(name)# Write the name to names.txt 
     f.write("\n") 
     f.close() 
else: 
    #if file exists, use it to load name, else ask user 
    with open(external_file, "r+") as f:# r+ open a file for reading & writing 
     lines = f.read().split('\n') # split the names 
     print lines 
     if username in lines: #Check if the file has any username as 'testuser' 
      print "Hi {}".format(username) 
     else: # If there is no username as 'testuser' then ask for a name 
      name = raw_input("What's your name?") 
      f.seek(0,2) # Resolves an issue in Windows 
      f.write(name)# Write the name to names.txt 
      f.write("\n") 
      f.close() 

使用file.seek()的原因是here

+0

即使名稱在.txt中,每次都要求輸入名稱? – user3735393

+0

是的,即使名稱在文件中,它也會詢問名稱,但如果名稱已在文件中,則不會將其附加到文件中。它詢問名稱是因爲它必須搜索文件中是否存在給定名稱。如果您沒有提供名稱,那麼代碼將如何知道要顯示的名稱? –

+0

我該如何做到這一點,所以它不要求名稱如果名稱在.txt中? – user3735393