Categories
Uncategorized

Edit a Bunch of Files – Python

I have four files in the folder and I want to write Number into each one of them.

file1.txt
file2.txt
file3.txt
file4.txt

So this bit of code will open each one of them and write Number and the value of counter (so we know it’s doing it’s thing).

import glob

counter=1

for filename in glob.glob("*.txt"):
	with open(filename, mode='w', buffering=-1) as f:
		f.write("Number "+str(counter))
		f.close()
		counter+=1

We cd to the folder and run the script.

The result should be

#file1.txt
Number 1
#file2.txt
Number 2
#file3.txt
Number 3
#file4.txt
Number 4

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s