1

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>')
4
  • You can pass the name as a variable and then attach it to the string there Commented Mar 21, 2022 at 10:25
  • Have you tried file = open(r'C:\Users\hu170f\Documents\TEST1\'+f)? Commented Mar 21, 2022 at 10:26
  • @Kristian yes I did that but it's not working Commented Mar 21, 2022 at 10:36
  • @MananAdhvaryu how do I do it. Can you help. Commented Mar 21, 2022 at 10:36

2 Answers 2

1
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())

Sign up to request clarification or add additional context in comments.

2 Comments

If I just have to print the file path along with file the name it is working fine. May be I haven't put up my question correctly. under the for loop I want to open the file one by one using command : file = open(r'<entire filepath>').
@shikha check now . I have opened a dir of txt files and am able to print.
0
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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.