我正在努力从我的函数中删除这个错误,它说函数不应该调用 'readlines'

问题描述

我正在努力从我的函数删除这个错误,它说函数不应该调用“readlines

有人可以帮助我吗?我一直在尝试修复此错误,但无法解决

我在下面列出了:

  1. 我们必须为此代码处理的 number.txt 文件
  2. 我正在接受的测试,也就是我必须遵守的条件
  3. 我的代码
  4. 样品测试

所以我的问题很容易理解。

使用本问题中的 numbers.txt 文件

1

2

6

7

3

4

5

6

7

8

9

9

10

11

12

13

我正在测试什么,应该遵循:(条件)

Test varIoUs parameters: '1'

OK

Test varIoUs parameters: '3 1 2'

OK

Test varIoUs parameters: 'numbers file variable'

OK

Test for calls to forbidden Python functions: 'input'

OK

Test for calls to forbidden Python functions: 'readlines'

ERROR:

function should not call 'readlines'

Test for calls to forbidden Python functions: 'open'

OK

Test for calls to forbidden Python functions: 'close'

OK

Test function docstring documentation:

OK

Test for multiple returns:

OK

Test that the function does not hard code the length of the file:

OK

Test for misuse of function name:

OK

代码

def append_increment(fh):

    """
    -------------------------------------------------------
    Appends a number to the end of the fh. The number appended
    is the last number in the file plus 1.
    Assumes file is not empty.
    Use: num = append_increment(fh)
    -------------------------------------------------------
    Parameters:
        fh - file to search (file handle - already open for reading/writing)
    Returns:
        num - the number appended to the file (int)
    ------------------------------------------------------
    """
    fh.seek(0)
    file_contents = fh.readlines()
    num = int(file_contents[-1]) + 1
    fh.write(str(num))
    return num

样品测试:

打开文件'numbers.txt'进行读写

附加了 14 个

解决方法

您确定,您以正确的模式打开了文件吗?
我现在正在使用 'at+' 作为模式并且它可以工作。那么你必须在每个新数字后添加一个换行符以避免数字堆叠。但这不是什么大问题。
这是我目前得到的:

def append_increment(fh):
    fh.seek(0)
    file_contents = fh.readlines()
    num = int(file_contents[-1]) + 1
    fh.write(str(num) + "\n")   # don't forget a newline after every new number
    return num
  
fh = open ( 'increment-number-file.txt','at+' )
append_increment(fh)
fh.close()

print ( open ( 'increment-number-file.txt','rt' ).read() )