Python 3.x 对于循环也是一样,使用.write()给出两个不同的结果

Python 3.x 对于循环也是一样,使用.write()给出两个不同的结果,python-3.x,Python 3.x,这是我第一次问问题,所以如果我做错了,请告诉我(post wise) 我试图创建一个写入.txt的函数,但在从模块内调用它和直接在shell中写入同一个循环之间,我似乎得到了两个截然不同的结果。代码如下: def function(para1, para2): #para1 is a string that i am searching for within para2. para2 is a list of strings with open("str" + para1 +".txt"

这是我第一次问问题,所以如果我做错了,请告诉我(post wise)

我试图创建一个写入.txt的函数,但在从模块内调用它和直接在shell中写入同一个循环之间,我似乎得到了两个截然不同的结果。代码如下:

def function(para1, para2): #para1 is a string that i am searching for within para2. para2 is a list of strings
    with open("str" + para1 +".txt", 'a'. encoding = 'utf-8') as file:
    #opens a file with certain naming convention

        n = 0
        for word in para2:
            if word == para1:
                file.write(para2[n-1]+'\n')
                print(para2[n-1]) #intentionally included as part of debugging
            n+=1

function("targetstr". targettext) 
#target str is the phrase I am looking for, targettext is the tokenized text I am
#looking through. this is in the form of a list of strings, that is the output of
#another function, and has already been 'declared' as a variable 
当我在shell中定义这个函数时,会出现正确的单词。但是,当我通过模块(在shell中)调用同一个函数时,shell中没有显示任何内容,文本文件显示一组数字(例如:“s93161),并且没有新行

我甚至在模块中声明函数之后加入了一个print语句,并对print语句之外的所有语句进行了注释,但是在调用它时shell中没有任何内容。但是,数字仍然显示在文本文件中

我猜在调用函数时,如何定义参数或如何输入参数存在问题

作为参考,以下是所需的输出:

”她说

艾希礼

那里

基蒂

科茨

“让


PS:抱歉,如果这不是很清楚,因为我在讲python方面的知识非常有限

我已经找到了解决问题的方法。事实证明,在编译器识别对模块中的函数所做的更改之前,我需要关闭shell并重新启动所有内容。感谢那些关注这个问题的人和那些试图提供帮助的人。

为什么不调试自己的代码呢?你在发布之前试过调试它吗?你最终必须学会这样做。看,是的。如守则所述。也许这不是最严格的调试,对此我深表歉意。很抱歉,我没有问那些让你兴奋的编程问题,因为我的知识有限,我只知道,如果这是对那些认真学习代码的人的态度,将无助于培养一个热爱代码的社区。