简体   繁体   English

从文件指针读取文件而不使用 readlines

[英]read file from file pointer without using readlines

can someone help me fix this code I keep getting this error, I'm struggling.有人可以帮我修复这个代码我一直收到这个错误,我很挣扎。

for every code I practice, I keep getting the same error对于我练习的每一个代码,我都会遇到同样的错误

This is the customers.txt file for this question that we are supposed to work with这是我们应该处理的这个问题的customers.txt文件

12345,Tom,Black,300.00,1998-01-30
23456,Alice,Smith,1200.50,1998-02-20
14567,Jane,White,900.00,1998-07-01
43564,Weilin,Zhao,450.25,1998-01-03
45432,Bina,Mehta,278.95,1998-03-21

def customer_first(fh):
    record = None
    lines = fh.readlines()
    i = 0
    while i < len(lines):
        line = lines[i]
        values = line.rstrip('\n').split(',')
        if record == None or values[4] < record[4]:
            record = values
        i += 1
    return record

... ...

Sample testing:样品测试:

Find customer with earliest sign-in:查找最早登录的客户:

['43564', 'Weilin', 'Zhao', '450.25', '1998-01-03'] ['43564', '伟林', '赵', '450.25', '1998-01-03']

this is the error I keep getting down below.这是我不断下降的错误。

Test for calls to forbidden Python functions: 'readlines'测试对禁止 Python 函数的调用:'readlines'

ERROR:错误:

function should not call 'readlines' function 不应调用“readlines”

these are all the things I'm being tested on in my code:这些是我在代码中测试的所有内容:

Test various parameters: 'customers file variable'测试各种参数:'客户文件变量'

OK好的

Test for calls to forbidden Python functions: 'input'测试对禁止 Python 函数的调用:“输入”

OK好的

Test for calls to forbidden Python functions: 'print'测试对禁止 Python 函数的调用:“打印”

OK好的

Test for calls to forbidden Python functions: 'readlines'测试对禁止 Python 函数的调用:'readlines'

ERROR:错误:

function should not call 'readlines' function 不应调用“readlines”

Test for calls to forbidden Python functions: 'open'测试对禁止 Python 函数的调用:'open'

OK好的

Test for calls to forbidden Python functions: 'close'测试对禁止 Python 函数的调用:“关闭”

OK好的

Test function docstring documentation:测试 function 文档字符串文档:

OK好的

Test for multiple returns:测试多重回报:

OK好的

Test that the function does not use 'for':测试 function 不使用“for”:

OK好的

Test that the function does not hard code the length of the file:测试 function 没有硬编码文件的长度:

OK好的

Test for misuse of function name:测试误用 function 名称:

OK好的

Your grading system might expect this, as an alternative to using .readlines ():作为使用.readlines () 的替代方法,您的评分系统可能会期望这样做:

def customer_first(fh):
    record = None
    lines = fh.read().split('\n')
    i = 0
    while i < len(lines):
        line = lines[i]
        values = line.split(',')
        if record == None or values[4] < record[4]:
            record = values
        i += 1
    return record

Here, we call .read() to read the whole file in at once, and then .split() it into individual lines for each line break.在这里,我们调用.read()一次读取整个文件,然后.split()将每个换行符分成单独的行。 This is essentially what .readlines() probably does under the hood, and is the most direct replacement for your code that doesn't use that method.这本质上是.readlines()可能在幕后所做的,并且是不使用该方法的代码的最直接替代品。


Your grading system might also be expecting you to do this:您的评分系统也可能希望您这样做:

def customer_first(fh):
    record = None
    i = 0
    line = fh.readline()
    while line != '':
        values = line.rstrip('\n').split(',')
        if record == None or values[4] < record[4]:
            record = values
        line = fh.readline()
    return record

File.readline() is similar to File.readlines() except that it returns only one line, and returns an empty string if you've reached the end of the file. File.readline()File.readlines() () 类似,只是它只返回一行,如果到达文件末尾则返回一个空字符串。


Another alternate solution is to iterate through the file with next() , and use a try / except block to catch a StopIteration (which is how for loops actually work under the hood).另一种替代解决方案是使用next()遍历文件,并使用try / except块来捕获StopIteration (这就是for循环在后台实际工作的方式)。 This is a more complicated, more advanced, and more niche method, though, which I think it's unlikely your teacher expects you to be using here unless this is something you've just learned about:不过,这是一种更复杂、更先进、更小众的方法,我认为你的老师不太可能希望你在这里使用它,除非这是你刚刚学到的东西:

def customer_first(fh):
    record = None
    i = 0
    try:
        line = next(fh)
        while line != '':
            values = line.rstrip('\n').split(',')
            if record == None or values[4] < record[4]:
                record = values
            line = next(fh)
    except StopIteration
        return record

I'd like to impress upon you that using for loops when possible is generally good practice, using .readlines() in general is usually not bad practice when simply iterating over the file in a for loop isn't sufficient, and you shouldn't take this assignment as a sign to avoid doing these things in the future.我想给你留下深刻印象的是,在可能的情况下使用for循环通常是一种好习惯,当简单地在for循环中迭代文件是不够的时,使用.readlines()通常通常不是坏习惯,你应该'不要把这个任务作为一个标志,以避免将来做这些事情。 If the assignment doesn't tell you what tool you're supposed to be using, and the recent lectures you've had in class haven't covered one of the above intending to clue you into it, then it's my opinion this is a bad assignment.如果作业没有告诉你应该使用什么工具,并且你最近在 class 上的讲座没有涵盖上述内容之一,旨在让你了解它,那么我认为这是一个错误的分配。

Also, your code probably has a logic error (try record == None and values[4] < record[4] ), but that's not the issue you're asking about, and once the grading system starts actually running your code, you'll get different error messages that would probably lead you to figuring it out anyway.此外,您的代码可能存在逻辑错误(尝试record == None and values[4] < record[4] ),但这不是您要问的问题,一旦评分系统开始实际运行您的代码,您' 会收到不同的错误消息,这些错误消息可能会导致您无论如何都要弄清楚。

If you really can't use readlines() or the csv module then certainly you can loop over the file such as:如果您真的不能使用 readlines()或 csv 模块,那么您当然可以遍历文件,例如:

data=[line.split(',') for line in fh.read().splitlines()]
>>> data
[['12345', 'Tom', 'Black', '300.00', '1998-01-30'], ['23456', 'Alice', 'Smith', '1200.50', '1998-02-20'], ['14567', 'Jane', 'White', '900.00', '1998-07-01'], ['43564', 'Weilin', 'Zhao', '450.25', '1998-01-03'], ['45432', 'Bina', 'Mehta', '278.95', '1998-03-21']]

Since those are ISO 8601 style dates, no conversion from text needed.由于这些是ISO 8601样式的日期,因此不需要从文本转换。 You can get the min this way:您可以通过以下方式获得min

>>> min(data, key=lambda sl: sl[4])
['43564', 'Weilin', 'Zhao', '450.25', '1998-01-03']
 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM