Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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
add comment

2 Answers

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:
            outfile.write("\n")
            for line in infile:
                outfile.write("%s\n" % line.rstrip())

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

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.

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

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

Your Answer

 
discard

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.