在Python中读取文件错误,即使打印功能正在打印列表

时间:2011-04-13 23:34:15

标签: python

我一直在尝试编写此代码的不同方法,但无法通过此方法。目前程序将一直运行到write_names(list)函数并创建文件,print函数将打印排序列表。程序拒绝获取search_names()函数的用户输入,但它会打印我要求的任何内容。

调试突出显示: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()
'

提前致谢!

3 个答案:

答案 0 :(得分:1)

您的问题是upper是一个函数,而您没有调用它。 while中的search_names()应为:

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

答案 1 :(得分: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.'

永远不会退出(再也不会被重新分配)。尝试:

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

  

您选择的方法取决于方法   通常你会期望事件发生。   如果这个活动真的很特别   是一个错误(例如意外   文件结束),使用异常处理   更好,因为代码更少   在正常情况下执行。如果   事件经常发生,使用   检查的程序化方法   错误更好。在这种情况下,如果一个   异常发生,异常将   需要更长的时间来处理。

答案 2 :(得分:0)

  1. 评论以#开头,而不是'# - 您正在将标题的每一行都设为文档字符串。

  2. 您正在使用索引迭代列表,效率很低 - 只需迭代列表项。

  3. 调用变量list是不好的,因为它会阻止您访问list()数据类型。

  4. 使用with是open()的更可靠替代品.close()

  5. again.upper是一个功能参考 - 您必须调用该函数,即again.upper()

  6. 您永远不会更改again的值 - 这将是一个无限循环!

  7. 您测试if search in list但是然后执行try..except块,只有在列表中时才会失败(即您正在测试两次相同的故障)。

  8. #
    # 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()