You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用Haxe语言实现文件每行添加递增编号功能

Hey there! Let's tackle this problem—adding line numbers to each line of a text file is a common task, and there are straightforward ways to do it in several popular languages. Here are a few solutions you can pick from based on what you're comfortable with:

Python Solution

Python is perfect for this kind of text manipulation, thanks to its built-in tools. The enumerate() function makes numbering lines a breeze:

# Open the input file and read all lines
with open('input.txt', 'r') as infile:
    lines = infile.readlines()

# Write the numbered lines to a new output file
with open('output.txt', 'w') as outfile:
    for line_num, line_content in enumerate(lines, start=1):
        # Strip trailing newlines to avoid double line breaks, then format and write
        outfile.write(f"{line_num}: {line_content.rstrip()}\n")

How it works: enumerate(lines, start=1) pairs each line with a counter that starts at 1 (instead of the default 0). We use rstrip() to clean up the original line's newline character so we can add our own after formatting.

Bash (Command Line) Solution

If you're working in a Unix-like environment (Linux, macOS, WSL), you don't even need to write a full script—use the nl command, which was made for this exact job:

nl -s ": " input.txt > output.txt

Quick breakdown: The -s ": " flag sets the separator between the line number and text to ": " (replacing the default tab). If you want to number empty lines too, add the -ba flag:

nl -ba -s ": " input.txt > output.txt
JavaScript (Node.js) Solution

If you prefer using Node.js for your scripting needs, here's a simple implementation:

const fs = require('fs');

// Read the input file content
fs.readFile('input.txt', 'utf8', (readErr, fileContent) => {
    if (readErr) {
        console.error('Oops, failed to read the file:', readErr);
        return;
    }

    // Split content into lines, number them, then join back into a single string
    const numberedLines = fileContent.split('\n').map((line, index) => {
        // Optional: Skip numbering empty lines (remove the condition to number all lines)
        return line.trim() ? `${index + 1}: ${line}` : '';
    }).join('\n');

    // Write the result to the output file
    fs.writeFile('output.txt', numberedLines, (writeErr) => {
        if (writeErr) {
            console.error('Failed to write the numbered file:', writeErr);
            return;
        }
        console.log('Numbered file created successfully!');
    });
});

内容的提问来源于stack exchange,提问作者had

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:03:17