Python replaces a line of content in a file with code

PointCloud-Slam-Image-Web3
Python & Other
Published in
2 min readApr 19, 2024

--

replace_linefunction accepts as arguments the file path , the line number to replace, and the new contents. It first opens the file using the with openstatement and reads all the lines. It then checks if the given line number is valid, and if it is not, it prints an error message and returns. If the line number is valid, it replaces the contents of the corresponding line. Finally, it opens the file in write mode using the with openstatement and writes the modified contents to the file .

Please note that the above code assumes that line numbers in the file start counting from 0. If your file line numbers start counting from 1, adjust the line number parameter accordingly when using it.

# -*- coding: utf-8 -*-#




def replace_line(file_path, line_number, new_content):
with open(file_path, 'r') as file:
lines = file.readlines()

if line_number < 0 or line_number >= len(lines):
print("无效的行号")
return

lines[line_number] = new_content + '\n'

with open(file_path, 'w') as file:
file.writelines(lines)


# 使用示例
file_path = 'img_to_char.txt' # 替换的txt文件路径
line_number = 28 # 要替换的行号(从0开始计数)
new_content = 'This is the new content' # 替换的新内容

replace_line(file_path, line_number, new_content)

If you have any questions or customized development requirements, you can contact me Email or WhatsApp : lonlonago@foxmail.com

--

--

PointCloud-Slam-Image-Web3
Python & Other

Familiar with point cloud data and image processing, interested in web3, take customization or consulting needs, enjoy work remotely, lonlonago@foxmail.com