繁体   English   中英

在当前和子目录中的每个 Python 文件顶部添加行

[英]Add line on top of each Python file in current and sub directories

我在 Ubuntu 平台上,并且有一个包含 many.py 文件和子目录(也包含 .py 文件)的目录。 我想在 each.py 文件的顶部添加一行文本。 使用 Perl、Python 或 shell 脚本最简单的方法是什么?

find . -name \*.py | xargs sed -i '1a Line of text here'

编辑:根据 tchrist 的评论,处理带有空格的文件名。

假设您有 GNU find 和 xargs (因为您在问题上指定了 linux 标记)

find . -name \*.py -print0 | xargs -0 sed -i '1a Line of text here'

如果没有 GNU 工具,您将执行以下操作:

while IFS= read -r filename; do
  { echo "new line"; cat "$filename"; } > tmpfile && mv tmpfile "$filename"
done < <(find . -name \*.py -print)
for a in `find . -name '*.py'` ; do cp "$a" "$a.cp" ; echo "Added line" > "$a" ; cat "$a.cp" >> "$a" ; rm "$a.cp" ; done
import os
for root, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith('.py')
            file_ptr = open(file, 'r')
            old_content = file_ptr.read()
            file_ptr = open(file, 'w')
            file_ptr.write(your_new_line)
            file_ptr.write(old_content)

据我所知,您不能在 python 中插入文件的开头或结尾。 仅重写或 append。

    #!/usr/bin/perl

    use Tie::File;
    for (@ARGV) {
        tie my @array, 'Tie::File', $_ or die $!; 
        unshift @array, "A new line";        
    }

要递归处理目录中的所有.py文件,请在 shell 中运行此命令:

find. -name '*.py' | xargs perl script.pl

这将

  1. 从当前工作目录开始递归遍历所有目录
  2. 仅修改文件名以 '.py' 结尾的文件
  3. 保留文件权限(与open(filename,'w')不同。)

fileinput还为您提供了在修改原始文件之前备份原始文件的选项。


import fileinput
import os
import sys

for root, dirs, files in os.walk('.'):
    for line in fileinput.input(
            (os.path.join(root,name) for name in files if name.endswith('.py')),
            inplace=True,
            # backup='.bak' # uncomment this if you want backups
            ):
        if fileinput.isfirstline():
            sys.stdout.write('Add line\n{l}'.format(l=line))
        else:
            sys.stdout.write(line)

使用 Perl、Python 或 shell 脚本最简单的方法是什么?

我会使用 Perl,但那是因为我知道 Perl 比我知道的 Python 要好得多。 哎呀,也许我会在 Python 中这样做只是为了更好地学习它。

最简单的方法是使用您熟悉并且可以使用的语言。 而且,这也可能是最好的方法。

如果这些都是 Python 脚本,我认为你知道 Python 或者可以接触到一群知道 Python 的人。 所以,你最好在 Python 中做这个项目。

但是,也可以使用shell 脚本,如果您知道 shell 最好,请成为我的客人。 这是一个完全未经测试的 shell 脚本,就在我的脑海中:

find . -type f -name "*.py" | while read file
do
    sed 'i\
I want to insert this line
' $file > $file.temp
  mv $file.temp $file
done

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM