[英]Open up multiple files in a folder in python for read/write
So if I have a data folder that has, say 15 txt files within it, how can i open up multiple txt files at the same time witin that data folder in one function and another set within another? 因此,如果我的数据文件夹中包含15个txt文件,那么如何在一个功能中同时打开该数据文件夹,而在另一个功能中同时打开多个txt文件呢?
So I wrote this: 所以我这样写:
with open("data/datafile.csv" , "r") as f :
reader = csv.reader(f)
return list(reader)
So how can I do that same thing but with several files at the same time? 那么,如何同时执行多个文件操作呢?
If it is okay to not really do it all at the same time , all you could do is to put your reading into its own function (ie read_csv
) then get all txt files in one directory and call your function for each file you find in the directory: 如果可以完全不同时执行所有操作, 则您可以做的就是将自己的阅读内容放入自己的函数(即
read_csv
)中,然后将所有txt文件放在一个目录中,并为找到的每个文件调用函数目录:
import os
def read_all_files(directory);
return [read_csv(f) for f in os.listdir(directory) if f.endswith(".txt")]
This will call a function read_csv
for each file that ends with ".txt" in the passed directory, and put it all into a big list which is returned. 这将为传递的目录中每个以“ .txt”结尾的文件调用一个
read_csv
函数,并将其全部放入返回的大列表中。
if it is important to have more files open at same time, then: 如果同时打开更多文件很重要,则:
with open("data/datafile.csv" , "r") as f:
with open("data/datafile2.csv" , "r") as f2:
f.read()
f2.read()
or 要么
f = open("data/datafile.csv" , "r")
f2 = open("data/datafile2.csv" , "r")
f.read()
f2.read()
f.close()
f2.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.