[英]How to open multiple files in loop, in python
I'm new to python.我是 python 的新手。 I'm want to open multiple files in Python.我想在 Python 中打开多个文件。 I'm can open each of them with open()
function.我可以用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.在live_filename()
function 中有很多文件。
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.我认为live
变量是一个不能连接 str 的元组。 what should i do?我应该怎么办?
Open each just as you did for one, and then append them to a list:像打开一个一样打开每个,然后append将它们放到一个列表中:
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.现在, all_files[0]
保存第一个加载的文件, all_files[1]
保存第二个,依此类推。
"D:\my_data"
.
假设它是"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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.