Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and write multiple files?

Tags:

python

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 read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for n number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.

like image 218
user17451 Avatar asked Oct 16 '08 11:10

user17451


People also ask

How do I read multiple files at once in Python?

Steps Needed Steps used to open multiple files together in Python : Both the files are opened with open() method using different names for each. The contents of the files can be accessed using readline() method. Different read/write operations can be performed over the contents of these files.


1 Answers

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()
like image 192
Mapad Avatar answered Oct 31 '22 01:10

Mapad