在Python中读取文件错误,尽管print函数打印了列表

0 投票
3 回答
516 浏览
提问于 2025-04-16 15:42

我一直在尝试不同的方法来写这段代码,但总是卡在这里。目前程序可以运行到write_names(list)这个函数,创建文件,并且打印出排序后的列表。但是程序就是不接受用户输入来执行search_names()这个函数,虽然我让它打印任何内容它都能做到。

调试时发现的问题是:while index < len(list),而调试输出只显示“读取文件错误”。希望有人能帮我看看我哪里出错了。

'#  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()
'

提前谢谢大家!

3 个回答

0

不要这样做:

#strip \n from each element
index = 0
while index < len(list):
    list[index] = list[index].rstrip('\n')
    index += 1
return list

可以用这个列表推导式来代替:

lines = infile.readlines()
infile.close()

return [ line.strip() for line in lines ]

补充说明:

看起来你在用索引和while循环,但其实可以用for循环来做。

不要这样:

while index < len(list):
    print list[index]
    index += 1

用这个:

    # using name_list instead of list
    for name in name_list:
        print name

另外,你的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.'

它永远不会退出(因为again从来没有被重新赋值)。试试:

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)?: ')

或者:

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()

这就引出了一个问题:什么时候用异常捕获,什么时候用if语句:

来自 msdn

你选择的方法取决于你预计事件发生的频率。如果这个事件真的很特殊,并且是个错误(比如意外的文件结束),那么使用异常处理会更好,因为在正常情况下执行的代码会更少。如果这个事件经常发生,使用程序化的方法来检查错误会更好。在这种情况下,如果发生异常,处理异常的时间会更长。

0
  1. 注释应该以 # 开头,而不是 '# - 这样会让你的每一行头部都变成文档字符串。

  2. 你在用索引来遍历列表,这样效率不高 - 直接遍历列表里的项目就可以了。

  3. 把变量命名为 list 是不好的,因为这样会让你无法使用 list() 这个数据类型。

  4. 使用 with 是一个更可靠的替代方法,比起用 open() .. close()

  5. again.upper 是一个函数引用 - 你需要调用这个函数,也就是 again.upper()

  6. 你从来没有改变 again 的值 - 这样会导致无限循环!

  7. 你测试 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()
1

你的问题是 upper 是一个函数,但你没有调用它。在 search_names() 里的 while 循环应该这样写:

while again.upper() == 'Y':

撰写回答