3
votes

Brand new to Python, first time poster, be easy on me please! I would like to insert a line of text into all files of a specific extension (in the example, .mod) within the current folder. It can point to a specific folder if that is easier.

Below is something that I copied and modified, it is doing exactly what I need for one specific file, the part about replacing sit with SIT is completely unnecessary, but if I remove it the program doesn't work. I have no idea why that is, but I can live with that.

import sys, fileinput

for i, line in enumerate(fileinput.input('filename.mod', inplace=1)):  
    sys.stdout.write(line.replace('sit', 'SIT'))    
    if i == 30: sys.stdout.write('TextToInsertIntoLine32' '\n') #adds new line and text to line 32  

My question is, how do I run this for all files in a directory? I have tried replacing the filename with sys.argv[1] and calling the script from the command line with '*.mod' which did not work for me. Any help would be appreciated.

4

4 Answers

1
votes

You could use glob.glob to list all the files in the current working directory whose filename ends with .mod:

import fileinput
import glob
import sys

for line in fileinput.input(glob.glob('*.mod'), inplace=True):
    sys.stdout.write(line.replace('sit', 'SIT'))
    if fileinput.filelineno() == 32:
        #adds new line and text to line 32      
        sys.stdout.write('TextToInsertIntoLine32' '\n')
2
votes

You can do like this:

import os
folder = '...'   # your directory
files = [f for f in os.listdir(folder) if f.endswith('.mod')]

Then you can get a list of files with the extension '.mod', you can run your function for all files.

1
votes

You can use os.walk function:

for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if file.endswith(".mod"):
             filepath = os.path.join(root, file)
             with open(filepath, 'r', encoding='utf-8') as f:
                 text = f.read()
                 print('%s read' % filepath)
             with open(filepath, 'w', encoding='utf-8') as f:
                 f.write(text.replace('sit', 'SIT'))
                 print('%s updated' % filepath)
0
votes

Easy: you don't have to specify a filename. fileinput will take the filenams from sys.argv by default. You don't even have to use enumerate, as fileinput numbers the lines in each file:

import sys, fileinput
for line in fileinput.input(inplace=True):
    sys.stdout.write(line.replace('sit', 'SIT'))
    if fileinput.filelineno() == 30:
        sys.stdout.write('TextToInsertIntoLine32' '\n')