3

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 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.