Zoltán Fodor
Zoltán Fodor

Reputation: 123

Write to every files in a directory with loop

With the code below I have made a htmlfiles.txt that contains HTML filenames in a directory:

import os
entries = os.listdir('/home/stupidroot/Documents/html.files.test')
count=0
for line in entries:
    count += 1
    f = open("htmlfiles.txt", "a")
    f.write(line + "\n")
    f.close()

In the second phase I want to make modification in every file like this:

lines = open('filename.html').readlines()
open('filename.html', 'w').writelines(lines[20:-20])

This code deletes the first and the last 20 lines in a HTML file.

I just want to make with all files with for loop simple.

Upvotes: 1

Views: 32

Answers (1)

azro
azro

Reputation: 54148

You just need to open the htmlfiles.txt file, and read each filename from each line and do your stuff :

with open("htmlfiles.txt") as fic:
    for filename in fic:
        filename = filename.rstrip()
        lines = open(filename).readlines()
        open(filename, 'w').writelines(lines[20:-20])

Upvotes: 1

Related Questions