您可以嘗試這樣做,首先簡單地詢問用戶的名稱,然後檢查文件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。
您能否詳細說明您面臨的問題?當代碼作爲聊天機器人在線併爲每個用戶使用一個.txt時,出現問題的意思是什麼,因此會向每個用戶致電其已被告知的第一個名稱。另請注意修復代碼的標識! –
@ user3735393你的代碼中有些東西沒有意義......例如,如果'external_file'不是文件(你可能應該使用'os.path.exists',而不是'os.path.isfile '),你試圖打開它(這可能會失敗,因爲該文件可能不存在),然後什麼都不做('通過')。那有什麼意義呢?你的例子最後還有一個'else'塊,沒有任何相應的'if',我猜測這是一個縮進問題。 – dano
@dano,如果文件不存在,它會失敗嗎? –