说,找方法

2024-04-26 12:27:27 发布

您现在位置:Python中文网/ 问答频道 /正文

使用seek()和read()方法从索引列表中检索隐藏代码。你知道吗

这是代码行为的示例:

>>>getCode("Da Vinci Code.txt", [4, 992, -26, 1242, 332])
'sofia'
def getCode(filename, indexes): 
    f=open(filename,'w')
    str=''
    for x in indexes:
        f.seek(x)
        str=str+f.read(x)
    return str
    f.close()

运行代码时出错:

Traceback (most recent call last):
File "Code", line 7, in getCode
File "/base/data/home/apps/s~pyschools2/888.418298200144529338/gaefile.py", line 223, in seek
raise IOError("Invalid argument")
IOError: Invalid argument

Tags: 方法代码inreadlinecodeseekfilename
1条回答
网友
1楼 · 发布于 2024-04-26 12:27:27

函数file.seek()file.read()似乎不支持否定参数。你知道吗

你可以把代码改成这个

with open('test.txt') as f:
    for i in [5, 1, 99, 2, 5]:
        f.seek(i, 0)        # offset 'i' chars starting at position 0 each time
        c = f.read(1)       # read only 1 char
        print(i, repr(c))

只使用正数。您需要更改索引才能使此版本的代码正常工作。你知道吗

相关问题 更多 >