How To Modify All Text Files In Folder With Python Script
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
Solution 1:
You can do like this:
import os
folder = '...' # your directory
files = [f for f inos.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.
Solution 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')
Solution 3:
You can use os.walk
function:
for root, dirs, files inos.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)
Solution 4:
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')
Post a Comment for "How To Modify All Text Files In Folder With Python Script"