I want to write a program for this: In a folder I have n number of files; first read one file and perform some operation then store result in a separate file. Then
I think what you miss is how to retrieve all the files in that directory. To do so, use the glob module. Here is an example which will duplicate all the files with extension *.txt to files with extension *.out
import glob
list_of_files = glob.glob('./*.txt') # create the list of file
for file_name in list_of_files:
FI = open(file_name, 'r')
FO = open(file_name.replace('txt', 'out'), 'w')
for line in FI:
FO.write(line)
FI.close()
FO.close()
This thing also works for reading multiple files, my file name is fedaralist_1.txt
and federalist_2.txt
and like this, I have 84 files till fedaralist_84.txt
And I'm reading the files as f.
for file in filename:
with open(f'federalist_{file}.txt','r') as f:
f.read()