简体   繁体   English

从一个函数返回所有可能的输出,然后在另一个函数中使用它

[英]return all possible outputs from a function then use it in another function

The purpose of this code is to read a directory which includes 5 files, then print these files names,But when I tried to do that I got weird result. 这段代码的目的是读取一个包含5个文件的目录,然后打印这些文件名。但是当我尝试这样做时,却得到了奇怪的结果。

ps [This is experience not real code and meant to return all possible outputs from a function then use it in another function to do something with it within the same class] ps [这不是真正的代码经验,它打算从一个函数返回所有可能的输出,然后在另一个函数中使用它在同一类中对其进行某些操作]

Here is the code: 这是代码:

import os


class Data:
    def __init__(self):
        self.dir = r"C:\Users\Sayed\Desktop\script\New folder"

    def files(self):
        os.chdir(self.dir)
        for files in os.listdir(self.dir):
            return files

    def df(self):
        files = self.files()
        for file in files:
            print(file)

Here is what I expected: 这是我所期望的:

file (1).txt 档案(1).txt

file (2).txt 文件(2).txt

file (3).txt 档案(3).txt

file (4).txt 档案(4).txt

file (5).txt 档案(5).txt

Here is the output: 这是输出:

f F

i 一世

l

e Ë

(

1 1

)

.

t Ť

x X

t Ť

os.listdir() returns a list of the files so you don't need to iterate over it. os.listdir()返回文件列表,因此您无需对其进行迭代。 Change your files function to this: files功能更改为此:

def files(self):
    os.chdir(self.dir)
    files = os.listdir(self.dir)
    return files

Your first return() leads to the loop break, hence saving only 1 filename instead of all of them. 您的第一个return()会导致循环中断,因此仅保存1个文件名而不是所有文件名。 Then, since str() is an iterable type, for() loop loops through it in an absolute correct way. 然后,由于str()是可迭代的类型,因此for()循环以绝对正确的方式循环通过它。

I suggest you'd want to do the following: 我建议您要执行以下操作:

def files(self):
    output = []
    os.chdir(self.dir)
    for files in os.listdir(self.dir):
        output.append(files)
    return output

You might want to read more on Iterables and Iterators . 您可能需要阅读有关Iterables和Iterators的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM