繁体   English   中英

如何在循环中动态创建变量名以分配给 python 3 中的文件名

[英]How do I dynamically create a variable name in a loop to assign to a file name in python 3

我对编程和 Python 还是比较陌生。 但我确信这一定是可能的,但我的搜索并没有找到我正在寻找的东西。

在我的当前目录中,我有 6 个 PDF 文件,我希望通过下面的循环读取这些文件。

我想做的是用一个新的变量名打开每个 PDF,你可以看到它被想象成pdf[1-6]File.pdf

我可以在控制台中列出文件,并在我坚持中断以停止执行时通过代码将它们拉出来,但我一生都无法弄清楚如何创建变量名。 我认为像 "pdf" + str(i) + "File" 这样的东西会起作用,但我错过了一些东西。

代码如下 - 不完整但足够让你明白我在看什么:

#Open the PDF files in the current directory for
#reading in binary mode
def opensource():
    listOfFiles = os.listdir('.')
    pattern = "*.pdf"
    for entry in listOfFiles:
        if fnmatch.fnmatch(entry, pattern):
            # Works to here perfectly
            for i in range(len(entry)):
                # print(len(entry))
                # Trying to create the variable name with 
                # an incremental numeral in the file name
                "pdf" + i + "File" = open(entry, 'rb')

下面的这一点是我目前正在做的事情,它的背后很痛苦。 我确信它可以以编程方式完成

#This is the old way. Monolithic and horrid 
#Open the files that have to be merged one by one
pdf1File = open('file1.pdf', 'rb')
pdf2File = open('file2.pdf', 'rb')
pdf3File = open('file3.pdf', 'rb')
pdf4File = open('file4.pdf', 'rb')
pdf5File = open('file5.pdf', 'rb')
pdf6File = open('file6.pdf', 'rb')

感谢所有帮助。

谢谢

如果你打算在这个 for 循环之外使用文件指针,你可以很好地使用字典来做到这一点。

def opensource():
    listOfFiles = os.listdir('.')
    pattern = "*.pdf"
    file_ptrs = {}
    for entry in listOfFiles:
        if fnmatch.fnmatch(entry, pattern):
            # Works to here perfectly
            for i in range(len(entry)):
                # print(len(entry))
                # Trying to create the variable name with 
                # an incremental numeral in the file name
                file_ptrs["pdf" + str(i) + "File"] = open(entry, 'rb')

注意:始终建议在 python 中的“ with ”子句旁边使用 open 方法。一旦文件操作脱离上下文,它会关闭文件。

暂无
暂无

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

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