Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我需要将标准头内容附加到所有python文件的顶部_Python_Batch File_Comments - Fatal编程技术网

我需要将标准头内容附加到所有python文件的顶部

我需要将标准头内容附加到所有python文件的顶部,python,batch-file,comments,Python,Batch File,Comments,因此,我有一堆python文件(实际上有数百个),它们需要在顶部添加一个注释头,其中包含产品名称、许可证参考通知、版权信息和其他内容。以批处理方式执行此操作的最佳方式是什么?换句话说,是否有一个工具可以用来指定标题是什么,以及将此标题与*.py过滤器或类似的内容应用到哪个目录?顺便说一下,每个文件的所有头信息都是相同的。Bash批处理语法: for i in `find {DIRECTORY} -name "*.py"`; do cat - $i > /tmp/f.py <&

因此,我有一堆python文件(实际上有数百个),它们需要在顶部添加一个注释头,其中包含产品名称、许可证参考通知、版权信息和其他内容。以批处理方式执行此操作的最佳方式是什么?换句话说,是否有一个工具可以用来指定标题是什么,以及将此标题与*.py过滤器或类似的内容应用到哪个目录?顺便说一下,每个文件的所有头信息都是相同的。

Bash批处理语法:

for i in `find {DIRECTORY} -name "*.py"`; do
    cat - $i > /tmp/f.py <<EOF
{HEADER_BLOCK}
EOF
    mv /tmp/f.py $i
done
'find{DIRECTORY}-name“*.py”中的i的
;做
cat-$i>/tmp/f.pyBash批处理语法:

for i in `find {DIRECTORY} -name "*.py"`; do
    cat - $i > /tmp/f.py <<EOF
{HEADER_BLOCK}
EOF
    mv /tmp/f.py $i
done
'find{DIRECTORY}-name“*.py”中的i的
;做

cat-$i>/tmp/f.py您实际上可以使用python本身来遵循python的方式

要在文件前添加或附加一些文本,请使用:

with open('filename.py','rb') as f:
    text = f.read()
    text = prependText + text
    text = text + postText
    // whatever you want to manipulate with the code text
with open('filename.py','wb') as f:
    f.write(text)

由于python模块通常演示树状结构,因此始终可以使用walk函数(os.path.walk)导航到任何深度级别,并根据路径和/或文件名应用任何自定义逻辑

实际上,您可以使用python本身来遵循python的方式

要在文件前添加或附加一些文本,请使用:

with open('filename.py','rb') as f:
    text = f.read()
    text = prependText + text
    text = text + postText
    // whatever you want to manipulate with the code text
with open('filename.py','wb') as f:
    f.write(text)

由于python模块通常演示树状结构,因此始终可以使用walk函数(os.path.walk)导航到任何深度级别,并根据路径和/或文件名应用任何自定义逻辑

如果您希望使用python本身而不是批处理方法,那么可以编写一个非常简化的版本,如下所示:

import os, sys

def main():
    HEADER = '''# Author: Rob
# Company: MadeupOne
# Copyright Owner: Rob
'''

    filelist = []
    for path, dir, files in os.walk(sys.argv[1]):
        for file in files:
            if file.endswith('.py'):
                filelist.append(path + os.sep + file)

        for filename in filelist:
            try:
                inbuffer = open(filename, 'U').readlines()
                outbuffer = [HEADER] + inbuffer

                open(filename, 'wb').writelines(outbuffer)
            except IOError:
                print 'Please check the files, there was an error when trying to open %s...' % filename
            except:
                print 'Unexpected error ocurred while processing files...'

if __name__ == '__main__': main()

只需传递包含要更改的文件的目录,它就会递归地将头文件前置到路径上的所有.py文件。

如果您希望使用python本身而不是批处理方法,则可以编写一个非常简化的版本,如下所示:

import os, sys

def main():
    HEADER = '''# Author: Rob
# Company: MadeupOne
# Copyright Owner: Rob
'''

    filelist = []
    for path, dir, files in os.walk(sys.argv[1]):
        for file in files:
            if file.endswith('.py'):
                filelist.append(path + os.sep + file)

        for filename in filelist:
            try:
                inbuffer = open(filename, 'U').readlines()
                outbuffer = [HEADER] + inbuffer

                open(filename, 'wb').writelines(outbuffer)
            except IOError:
                print 'Please check the files, there was an error when trying to open %s...' % filename
            except:
                print 'Unexpected error ocurred while processing files...'

if __name__ == '__main__': main()

只需传递包含要更改的文件的目录,它就会递归地将头添加到路径上的所有.py文件。

更新了上面的脚本,以使用python 3并忽略隐藏的文件夹

import os, sys

def main(path):
    HEADER = '''#!/usr/bin/python3

# Copyright : 2021 European Commission
# License   : 3-Clause BSD


'''

    filelist = []
    for path, dir, files in os.walk(sys.argv[1]):
        if '/.' not in path:
            for file in files:
                if file.endswith('.py'):
                    filelist.append(path + os.sep + file)
        
    for filename in filelist:
        try:
            inbuffer = open(filename, 'r').readlines()
            outbuffer = [HEADER] + inbuffer

            open(filename, 'w').writelines(outbuffer)
            print(f"Header is added to the file: '{filename}'.")
        except IOError:
            print('Please check the files, there was an error when trying to open %s...' % filename)
        except:
            print('Unexpected error ocurred while processing files...')


if __name__ == '__main__': main()

更新上述脚本以使用python 3并忽略隐藏文件夹

import os, sys

def main(path):
    HEADER = '''#!/usr/bin/python3

# Copyright : 2021 European Commission
# License   : 3-Clause BSD


'''

    filelist = []
    for path, dir, files in os.walk(sys.argv[1]):
        if '/.' not in path:
            for file in files:
                if file.endswith('.py'):
                    filelist.append(path + os.sep + file)
        
    for filename in filelist:
        try:
            inbuffer = open(filename, 'r').readlines()
            outbuffer = [HEADER] + inbuffer

            open(filename, 'w').writelines(outbuffer)
            print(f"Header is added to the file: '{filename}'.")
        except IOError:
            print('Please check the files, there was an error when trying to open %s...' % filename)
        except:
            print('Unexpected error ocurred while processing files...')


if __name__ == '__main__': main()

+1,尽管如果我们想保留文件开头可能存在的shebang和/或charset规范,可能需要一些额外的逻辑。+1,尽管如果我们想保留文件开头可能出现的shebang和/或charset规范,可能需要一些额外的逻辑。这实际上不是特定于Python的(除非您正在寻找一个Python库,而不是一个shell/批处理工具来为您做这件事)。除了不特定于Python之外,看起来你自己都没有做过任何尝试,这不是python特有的,对吧。我之所以标记python,是因为我正在处理python文件。martineau-我正在寻找一个工具或脚本来为我做这件事,因为我还有一百万其他更重要的事情要做。你有问题吗?我为什么要自己做呢?也许你没有足够的工作收入,有空余时间到你遇到的每一个老鼠洞里闲逛。这个板是为那些有问题的人准备的,以防你没有注意到。这并不是真正的Python专用的(除非你正在寻找一个Python库,而不是一个shell/批处理工具来为你做这件事?)。除此之外,不仅不是Python专用的,看起来你自己也没有做过任何尝试。它不是Python专用的,对的我之所以标记python,是因为我正在处理python文件。martineau-我正在寻找一个工具或脚本来为我做这件事,因为我还有一百万其他更重要的事情要做。你有问题吗?我为什么要自己做呢?也许你没有足够的工作收入,有空余时间到你遇到的每一个老鼠洞里闲逛。这个板是为那些有问题的人准备的,以防你没有注意到。哈!我应该知道python会是答案——我想这太明显了吧?谢谢,哈!我应该知道python会是答案——我想这太明显了吧?谢谢