【发布时间】:2021-03-27 17:39:30
【问题描述】:
我正在努力从我的函数中删除这个错误,它说函数不应该调用“readlines”
有人可以帮助我吗?我一直在尝试修复此错误但无法解决?
我在下面列出:
- 我们必须为此代码处理的 number.txt 文件
- 我正在接受测试,也就是我必须遵循的条件
- 我的代码
- 样品测试
所以我的问题很容易理解。
使用该问题中的 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
【问题讨论】:
-
作弊解决方案是
list(fh)而不是fh.readlines() -
成功了,非常感谢您的帮助!!