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?
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.
"D:\my_data"
.
Then, you can get all the filepaths of the files as in the script above.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.