向文件添加行号通常是指在文件的每一行前面添加一个唯一的数字标识,以便于阅读和参考。这在查看大型文本文件时尤其有用,因为它可以帮助用户快速定位到特定的行。
以下是一个使用Python脚本为文件添加行号的示例:
def add_line_numbers(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
with open(file_path + '.numbered', 'w') as output_file:
for i, line in enumerate(lines, start=1):
output_file.write(f"{i}: {line}")
# 使用示例
add_line_numbers('example.txt')
f"{i:<4}: {line}"
来确保行号占4个字符宽度。for line in file:
来逐行读取文件。open(file_path, 'r', encoding='utf-8')
来指定文件编码。通过以上方法,可以有效地为文件添加行号,并解决常见的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云