如何解决我正在努力从我的函数中删除这个错误,它说函数不应该调用 'readlines'
我正在努力从我的函数中删除这个错误,它说函数不应该调用“readlines”
我在下面列出了:
所以我的问题很容易理解。
使用本问题中的 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() )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。