我一直在嘗試編寫此代碼的不同方式,但無法通過此操作。目前該程序將一直運行到write_names(list)
函數並創建文件,打印功能將打印排序列表。該程序拒絕獲取search_names()
函數的用戶輸入,但它會打印我要求的任何內容。即使打印函數正在打印列表,但在Python中讀取文件錯誤
調試亮點:while index < len(list)
並且在調試I \ O中只聲明「讀取文件錯誤」。希望有人知道我做錯了什麼。
'# Abstract: This program creates a list of names. The list is printed,
'# sorted, printed again, written to file, and searched.
'#=============================================================================
'#define the main function
def main():
#try:
##open data file for read
#infile = open('names.txt', 'r')
#call get_names function
list = get_names()
#call print function
print_names(list)
#sort list
list.sort()
#print sorted list
print_names(list)
#write sorted list to new file
write_names(list)
#allow user to search list
search_names(list)
def get_names():
try:
infile = open('names.txt', 'r')
#read file contents into a list
list = infile.readlines()
#close file
infile.close()
#strip \n from each element
index = 0
while index < len(list):
list[index] = list[index].rstrip('\n')
index += 1
return list
except IOError:
print 'Read file error'
def print_names(list):
#print header
print '******************'
#print list line by line
index = 0
while index < len(list):
print list[index]
index += 1
return
def write_names(list):
#open file for writing
outfile = open('sortedNames.txt', 'w')
#write the list to the file
for item in list:
outfile.write(str(item) + '\n')
#close file
outfile.close()
def search_names(list):
#set user test variable
again = 'Y'
while again.upper == 'Y':
#get search from user
search = raw_input('Enter a name to search for: ')
#open list for search
if search in list:
try:
item_index = list.index(search)
print search, 'found.', item_index
except ValueError:
print search, 'not found.'
main()
'
在此先感謝!
我建議不要使用「list」,因爲它是一個內置函數。 – aukaost 2011-04-13 23:42:27