简体   繁体   English

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

[英]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: whilesearch_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语句的问题:

from msdn : 来自msdn

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. 在这种情况下,如果发生异常,则该异常将需要更长的时间来处理。

  1. Comments begin with # , not '# - you are making every other line of your header a docstring. 注释以#开头,而不是'# -您正在将标头的其他每一行作为文档字符串。

  2. You are using an index to iterate across lists, which is inefficient - just iterate on the list items. 您正在使用索引来遍历列表,这是低效率的-仅遍历列表项。

  3. Calling a variable list is bad because it prevents you from accessing the list() datatype. 调用变量list是不好的,因为它阻止您访问list()数据类型。

  4. Using with is a more reliable replacement for open() .. close() 使用with是open().. close()的更可靠替代方法

  5. again.upper is a function reference - you have to call the function, ie again.upper() . again.upper是一个函数引用-您必须调用该函数,即again.upper()

  6. You never change the value of again - this will be an infinite loop! 你永远不会改变的值again -这将是一个无限循环!

  7. 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.

相关问题 即使文件在同一目录中,Python 文件未找到错误 - Python File Not Found Error even though file is in same directory 即使元素在Python列表中也存在值错误 - Value error even though element is present inside the list in Python IndexError:列表索引超出范围,即使打印单个列表和索引似乎没有错误 - IndexError: list index out of range even though printing individual lists and index doesn't seem to have an error Python 打印函数中的函数打印 - Function printing in Print Function in Python Python:打印全局对象列表时,打印函数挂起 - Python: print function hang when printing global list of objects 即使两个选择都不是,输出也不会打印结果,但第一个选项是python列表中的正确选择 - Output does not print result even though the two choices are none but the first option is the right choice in python list Python 说它找不到我要重命名的文件,即使它可以读取文件名 - Python says it can't find the file I am trying to rename even though it can read the file name Python:即使文件正确,也没有这样的文件或目录 - Python: No such file or directory even though file is correct Python:即使它肯定存在,也不会在列表中找到字符串 - Python: will not find a string in a list even though it definitely is there 即使我使用了全局关键字,Python 也无法读取 function 中的全局变量 - Python cannot read global variable in function even though I used global keyword
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM