[英]Read file error in Python, even though print function is printing the list
I have been trying different ways of writing this code but cannot get past this. 我一直在尝试不同的方式来编写此代码,但无法超越。 Currently the program will run all the way to the write_names(list)
function and create the file, and the print function will print the sorted list. 当前,程序将一直运行到write_names(list)
函数并创建文件,而print函数将打印排序后的列表。 The program refuses to get the user input for the search_names()
function but it will print anything I ask it to. 该程序拒绝获取用户对search_names()
函数的输入,但会打印我要求的任何内容。
Debug highlights: while index < len(list)
and in the debug I\\O only states "read file error". 调试要点: while index < len(list)
且在调试I \\ O中仅声明“读取文件错误”。 Hopefully someone has an idea what I'm doing wrong. 希望有人知道我在做什么错。
'# 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()
'
Thanks in advance! 提前致谢!
Your issue is that upper
is a function, and you are not calling it. 您的问题是upper
是一个函数,您没有调用它。 Your while
in search_names()
should read: 你while
在search_names()
应为:
while again.upper() == 'Y':
instead of: 代替:
#strip \n from each element
index = 0
while index < len(list):
list[index] = list[index].rstrip('\n')
index += 1
return list
just use this list comprehension: 只需使用以下列表理解:
lines = infile.readlines()
infile.close()
return [ line.strip() for line in lines ]
edit: 编辑:
It looks like you are using an index and a while
loop where a for
loop can be used. 看起来您正在使用索引和while
循环,可以在其中使用for
循环。
Instead of: 代替:
while index < len(list):
print list[index]
index += 1
use: 采用:
# using name_list instead of list
for name in name_list:
print name
also, your search_names() function looks flawed: 另外,您的search_names()函数看起来有缺陷:
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.'
would never exit (again is never reassigned). 永远不会退出(再次不会重新分配)。 try: 尝试:
def search_names(names_list):
again = 'Y'
while again.upper() == 'Y':
s_name = raw_input('Enter a name to search for: ')
if s_name in names_list:
print s_name, 'found.', names_list.index(s_name)
else:
print search, 'not found.'
again = raw_input('Search for another name (Y|N)?: ')
or: 要么:
def search_names(names_list):
again = 'Y'
while again == 'Y':
s_name = raw_input('Enter a name to search for: ')
try:
idx = names_list.index(s_name)
print s_name, 'found.', idx
except ValueError:
print search, 'not found.'
again = raw_input('Search for another name (Y|N)?: ').upper()
Which brings up the issue of when to catch exceptions vs using an if statement: 这就提出了何时捕获异常与使用if语句的问题:
The method you choose depends on how often you expect the event to occur. 您选择的方法取决于您希望事件发生的频率。 If the event is truly exceptional and is an error (such as an unexpected end-of-file), using exception handling is better because less code is executed in the normal case. 如果事件确实是异常事件并且是错误(例如意外的文件结尾),则使用异常处理会更好,因为在正常情况下执行的代码较少。 If the event happens routinely, using the programmatic method to check for errors is better. 如果事件按常规发生,则使用编程方法检查错误会更好。 In this case, if an exception occurs, the exception will take longer to handle. 在这种情况下,如果发生异常,则该异常将需要更长的时间来处理。
Comments begin with #
, not '#
- you are making every other line of your header a docstring. 注释以#
开头,而不是'#
-您正在将标头的其他每一行作为文档字符串。
You are using an index to iterate across lists, which is inefficient - just iterate on the list items. 您正在使用索引来遍历列表,这是低效率的-仅遍历列表项。
Calling a variable list
is bad because it prevents you from accessing the list() datatype. 调用变量list
是不好的,因为它阻止您访问list()数据类型。
Using with
is a more reliable replacement for open() .. close() 使用with
是open().. close()的更可靠替代方法
again.upper
is a function reference - you have to call the function, ie again.upper()
. again.upper
是一个函数引用-您必须调用该函数,即again.upper()
。
You never change the value of again
- this will be an infinite loop! 你永远不会改变的值again
-这将是一个无限循环!
You test if search in list
but then do a try..except block which will only fail if it is not in the list (ie you are testing for the same failure twice). 您测试if search in list
然后执行try..except块,该块仅在不在列表中时才会失败(即,您两次测试相同的失败)。
. 。
#
# Operate on a list of names
#
def load_names(fname):
try:
with open(fname, 'r') as inf:
return [line.strip() for line in inf]
except IOError:
print "Error reading file '{0}'".format(fname)
return []
def print_names(namelist):
print '******************'
print '\n'.join(namelist)
def write_names(namelist, fname):
with open(fname, 'w') as outf:
outf.write('\n'.join(namelist))
def search_names(namelist):
while True:
lookfor = raw_input('Enter a name to search for (or nothing to quit): ').strip()
if lookfor:
try:
ind = namelist.index(lookfor)
print("{0} found.".format(lookfor))
except ValueError:
print("{0} not found.".format(lookfor))
else:
break
def main():
namelist = load_names('names.txt')
print_names(namelist)
namelist.sort()
print_names(namelist)
write_names(namelist, 'sorted_names.txt')
search_names(namelist)
if __name__=="__main__":
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.