在python脚本中使用sed命令替换文件的第一行

在python脚本中使用sed命令替换文件的第一行,python,sed,Python,Sed,我正在编写一个python脚本,该脚本需要将文件的第一行替换为另一行 #/bin/bash和#/usr/bin/custom_shell 只有第一行需要更改,我尝试在subprocess.call中使用sed命令,但没有成功,请有人建议一种可爱而简单的方法来执行此操作。您根本不需要使用sed和subprocess import os replacement, shebang_line = "#!/usr/bin/custom_shell\n", "" with open("InputFile.

我正在编写一个python脚本,该脚本需要将文件的第一行替换为另一行

#/bin/bash
#/usr/bin/custom_shell


只有第一行需要更改,我尝试在subprocess.call中使用sed命令,但没有成功,请有人建议一种可爱而简单的方法来执行此操作。

您根本不需要使用
sed
subprocess

import os
replacement, shebang_line = "#!/usr/bin/custom_shell\n", ""

with open("InputFile.txt") as input_file, open("tempFile.txt") as output_file:

    # Find the first non-empty line (which is assumed to be the shebang line)
    while not shebang_line:
        shebang_line = next(input_file).strip()

    # Write the replacement line
    output_file.write(replacement)

    # Write rest of the lines from input file to output file
    map(output_file.write, input_file)

# rename the temporary file to the original input file
os.rename("tempFile.txt", "InputFile.txt")

为什么不使用python打开文件,进行更改并将其写回文件?除非你的文件太大,无法保存在内存中

for i in files_to_change:
    with open(i,'rw') as f:
        lines = f.readlines()
        lines[lines.index("#!/bin/bash\n")] = "#!/usr/bin/custom_shell"
        f.seek(0)
        f.writelines(lines)
使用:

这将把放置写入标准输出。要使用替换的文本保存文件,请使用
-i
标志:

sed -i '' -e '1s:#!/bin/bash:#!/usr/bin/custom_shell:' yourfile.py

最好的方法是就地修改文件

import fileinput

for line in fileinput.FileInput("your_file_name", inplace=True):
    print("#!/usr/bin/custom_shell")
    break

这个问题似乎离题了,因为它是关于一种简单而可爱的方法,可以在不提供任何信息的情况下执行某些操作来诊断问题。这实际上应该使用一个临时文件名(即
tempfile
模块)。
import fileinput

for line in fileinput.FileInput("your_file_name", inplace=True):
    print("#!/usr/bin/custom_shell")
    break