首页 > 解决方案 > 尝试将斐波那契项添加到文件名时获取不完整的数据

问题描述

我有关于 load_fib、write_fib、fib 和 return_fib 的代码。我得到一个数字 n,需要加载最后计算的 fib 序列,并在文件名中添加 n 个额外的 fibonacci 项,并返回文件上写入的最后一个 fibonacci 数字。我想知道为什么我得到0数据而不是0 1 1 2尝试global_fib(3, filename)然后with open(filename, "r") as f: ... data = f.read()

fib_called = False
def global_fib(n, filename):
    global gf
    gf = load_fib(filename)
    i = 0
    write_fib(filename)
    while i < n:
        fib()
        write_fib(filename)
        i += 1
    return return_fib()

import os
def fib():
    global fib_called
    if len(gf) == 1:
        gf.append(1)
    else:
        gf.append(int(gf[-1] + gf[-2]))
    fib_called = not fib_called

def write_fib(filename):
    global fib_called
    if fib_called == True:
        filename.open('w')
        filename.write(str(gf[-1]) + ' ')
    fib_called = not fib_called

import os.path
def load_fib(filename):
    if os.path.exists(filename):
        filename.open('r')
        content == filename.read()
        return list(content)
    else:
        f = open(filename,'w')
        f.write('0' + ' ')
        return [0]

def return_fib():
    return gf[-1] 

标签: pythonpython-3.xfilenamesfibonaccios.path

解决方案


在您的load_fib函数中,当您分配包含文件数据的变量时会出现拼写错误 -

def load_fib(filename):
    if os.path.exists(filename):
        filename.open('r')
        content == filename.read() # <-- this line
        return list(content)

应该从 double equals 更改(用于测试相等性)

content == filename.read() 

单等于(赋值)

content = filename.read()

推荐阅读