Python列表仍在scop中时丢失值

2024-04-26 07:15:10 发布

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

请看下面用python编写的代码片段

import os

my_files = []
FOLDER_PATH = r'PATH_To_FOLDER'
for root, dirs, files in os.walk(FOLDER_PATH):
    #print(root)
    my_files = [root +'\\'+ f for f in files if f.endswith('.txt')]
    print(my_files[:]) #files are there in my_files
    #print(len(my_files)) #outputs 2

for f in my_files: #len(my_files) = 0 at this point, why?
    with open(f,'r') as ff:
    print(ff.read())

很明显,我的\文件仍在作用域中,但它应该保留它的值。但事实并非如此?你知道吗


Tags: topath代码inimportforlenos
3条回答

列表理解创建一个新的列表,然后重新分配变量来处理这个新列表。这非常像:

>>> a = [1, 2, 3]
>>> a = [4, 5, 6]

期待:

>>> a
[1, 2, 3, 4, 5, 6]

相反,您希望使用extend方法或+=将所有新值附加到现有列表上:

>>> a = [1, 2, 3]
>>> a.extend([4, 5, 6])
>>> a
[1, 2, 3, 4, 5, 6]

在您的例子中,看起来是这样的(注意,您可以从列表理解中删除[],将其转换为一个生成器表达式,在这种情况下,除了使代码更具可读性之外,这没有什么区别):

my_files.extend(root +'\\'+ f for f in files if f.endswith('.txt'))

使用列表.扩展。你知道吗

您正在做的是重新分配列表(在您的案例中是我的文件列表)。因此,在每个循环中,它的值都被重新分配,而不是添加到现有列表中。这就是列表.扩展来。你知道吗

my_files = []
    FOLDER_PATH = r'abc'
    for root, dirs, files in os.walk(FOLDER_PATH):
        my_files.extend(root +'/'+ f for f in files if f.endswith('.txt'))

    for f in my_files: #len(my_files) = 0 at this point, why?
        with open(f,'r') as ff:
            print(ff.read())

您需要使用list.extend将一个列表的内容添加到另一个列表中。你知道吗

目前,您只需在每次迭代中重新分配给相同的list变量,因此如果它为空,则只意味着os.walk的最后一次迭代没有返回任何文件。如果你周期性地改变它所指的内容,那么它是否在范围内并没有什么区别。你知道吗

from os import walk, path

my_files = []
FOLDER_PATH = r'.'
for root, dirs, files in walk(FOLDER_PATH):
    my_files.extend(path.join(root, f) for f in files if f.endswith('.txt'))

print(my_files)

for f in my_files:
    print('**** %s' % f)
    with open(f,'r') as ff:
        print(ff.read())

另外,使用os.path.join可以创建独立于平台的路径。你知道吗

相关问题 更多 >