twelsh37
twelsh37

Reputation: 301

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

I'm still relatively new to programming and Python. But I am sure this must be possible but my searches are not turning up what I'm looking for.

In my current directory, I have 6 PDF files that I wish to read in via the loop below.

What I would like to do is open each of the PDF's with a new variable name, as you can see it is imaginatively called pdf[1-6]File.pdf.

I can list the files in the console and pull them via the code when I stick breaks in to stop it executing but I can't for the life of me work out how to create the variable name. I thought something like "pdf" + str(i) + "File" would have worked but I'm missing something.

Code is below - not complete but enough so you get what I'm looking at:

#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 bit below is how I'm currently doing it and its a pain in the backside. I'm sure it can be done programmatically

#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')

All help gratefully received.

Thanks

Upvotes: 0

Views: 1143

Answers (1)

Arun Kaliraja Baskaran
Arun Kaliraja Baskaran

Reputation: 1086

If you are going to use the file pointer outside this for loop, you can very well use a dictionary to do that..

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')

Caution: Its always advisable to use the open method alongside of a "with" clause in python.. it takes care of closing the file once the file operation goes out of context.

Upvotes: 2

Related Questions