如何在目录中每个文件的开头添加新行?如何消除目录中每个文件每行末尾无用的空格和制表符?
答案1
这是我编写的一个非常基本的脚本。将 DIR 常量替换为包含文件的目录的路径。
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)
答案2
这是一个使用 bash 脚本的简单变体,该脚本在作为必须存在的参数传递的目录中每个文件的开头插入一个空行。
#!/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