简体   繁体   中英

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?

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:

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM