【问题标题】:I'm struggling to remove this error from my function where it says that the function shouldn't call 'readlines'我正在努力从我的函数中删除这个错误,它说函数不应该调用'readlines'
【发布时间】:2021-03-27 17:39:30
【问题描述】:

我正在努力从我的函数中删除这个错误,它说函数不应该调用“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

【问题讨论】:

  • 作弊解决方案是list(fh) 而不是fh.readlines()
  • 成功了,非常感谢您的帮助!!

标签: python computer-science


【解决方案1】:

你确定,你用正确的模式打开了文件吗?
我现在使用'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() )

【讨论】:

  • OP 的问题是硬件提交检查了某些被禁止的功能(出于某种原因),而不是代码不起作用。
猜你喜欢
  • 2021-05-11
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
相关资源
最近更新 更多