SSRSeln
SSRSeln

Reputation: 59

python file name as parameter from array

I need to declare filenames in an array and pass them to open with method in python.File name needs to be sent as parameter from the array. Please let me know if the code below is fine.

filenames= ["abc.txt", "def.txt", "ghi.txt"] 

Code for iterating

for file in filenames

    with open(file,'r')

My expectation is to iterate through the filenames and open them like

with open('abc.txt', 'r') #for first run

with open('def.txt', 'r') #for second run

with open('ghi.txt', 'r') #for third run

Upvotes: 0

Views: 246

Answers (3)

Harsh Prateek
Harsh Prateek

Reputation: 19

If your files are in the same location as the python program, the below snippet is a good reference.

filenames= ["abc.txt", "def.txt", "ghi.txt"]
for i in filenames:
    with open(i,"r"):
        #do something with files here

In case your files are located somewhere else, try providing the full path in the list. Or use a prefix like below:

filenames= ["abc.txt", "def.txt", "ghi.txt"]
path_prefix = <path here>
for i in filenames:
    with open(path_prefix + i,"r"):
        #do something with files here

Upvotes: -1

Harsha Biyani
Harsha Biyani

Reputation: 7268

You can try:

filenames= ["abc.txt", "def.txt", "ghi.txt"] 
for single_filename in filenames:
    with open(single_filename, 'r') as file_object:
        print file_object.readlines()

Upvotes: 2

DirtyBit
DirtyBit

Reputation: 16772

filenames= ["abc.txt", "def.txt", "ghi.txt"]

for i in range(len(filenames)):
    with open(filenames[i], 'r') as fileObj:
        # do the rest

Or just:

for file in filenames:
    with open(file, 'r') as fileObj:
        fileObj.readlines()
        # do the rest

Upvotes: 2

Related Questions