shikha
shikha

Reputation: 103

How to pass file name at run time in python

I have a directory which contains 4 .csv files at the moment. I am able retrieve their names using os lib in the code given below:

import os
fileNames = os.listdir(path)

for f in fileNames:
        print(f)

Now I want to pass the file names one by one in my open file command and do the related processing.

how do I pass file name in my command:

file = open(r'C:\Users\hu170f\Documents\TEST1\<filename to be passed>')

Upvotes: 1

Views: 921

Answers (2)

Don CorliJoni
Don CorliJoni

Reputation: 248

import os
path = r"C:\..."
filenames = os.listdir(path)

You can use the map function like a for loop, which only opens one method(The first parameter) and passes one after one element of this list(second parameter) to the method. The lambda function is like a method which executes the open function and returns the _io.TextIOWrapper. files contains a list of _io.TextIOWrapper.

files = list(map(lambda filename: open(f"{path}\{filename}"), filenames))

Upvotes: 0

balu
balu

Reputation: 1143

import os
dir_path = r'D:\text_dirs\\'
fileNames = os.listdir(dir_path)

for fn in fileNames:
    f = open(dir_path+fn, "r")
    print(f.read())

Upvotes: 1

Related Questions