Sign up ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

How do I add a new line at the beginning of every file I have in a directory? How do I eliminate useless spaces and tabs at the end of each line of each file in my directory?

share|improve this question

2 Answers 2

Here is a very basic script that I have put together. Replace the DIR constant with the path to the directory which contains the files.

import os

DIR = "" # Change to the directory which contains the files

for srcfile in os.listdir(DIR):
    original = os.path.join(DIR, srcfile)
    temp = os.path.join(DIR, "%s_tmp" % srcfile)
    with open(original) as infile:
        with open(temp, 'w') as outfile:
            for line in infile:
                outfile.write("%s\n" % line.rstrip())

    os.rename(temp, original)
share|improve this answer

Here's a simple variation using a bash script that inserts an empty line at the beginning of every file in a directory passed as an argument that must exist.

# requires one argument that is path to a directory whose files you want
# to add an initial line to

for f in $(ls $1)
    mv $1/$f $1/$f.orig
    echo -e "\t" > $1/$f
    cat $1/$f.orig >> $1/$f
    rm $1/$f.orig
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.