6

I'm new to python. I'm want to open multiple files in Python. I'm can open each of them with open() function. I'm not sure about formatting.

with open("/test/filename.css", "r") as f:
     s = f.readlines()
     print(s)

I'm can open one file, but I'm not sure how to open multiple files. This is the code that I have. In live_filename() function have many files.

inputfiles = live_filename()
    for live in inputfiles:
        with open("/test/............. .css, "r") as f:

I don't know how to put code formatting in space. and I think the live variable is a tuple can't concatenate str. what should i do?

2 Answers2

5

Open each just as you did for one, and then append them to a list:

import os

folderpath = r"D:\my_data" # make sure to put the 'r' in front
filepaths  = [os.path.join(folderpath, name) for name in os.listdir(folderpath)]
all_files = []

for path in filepaths:
    with open(path, 'r') as f:
        file = f.readlines()
        all_files.append(file)

Now, all_files[0] holds the first file loaded, all_files[1] the second, and so on.


UPDATE: for all files in the same folder: first, get the folder path (on Windows, like this). Suppose it's "D:\my_data". Then, you can get all the filepaths of the files as in the script above.
OverLordGoldDragon
  • 1
  • 9
  • 53
  • 101
1

You can do like this:

folder = "..." # Absolute path to folder in which the files reside
files_to_read = [("filename.css","FileName"),( "filename2.css","Filename2")]
for (file, _) in files_to_read:
    filepath = os.path.join(folder, file)
    with open(filepath, "r") as f:
        s = f.readlines()
        print(s)
MjZac
  • 3,476
  • 1
  • 17
  • 28