在文本文件中按行号替换特定行,可以使用编程语言中的文件读取和写入功能来实现。以下是一些常见编程语言的示例代码:
def replace_line(file_path, line_number, new_line):
with open(file_path, 'r') as file:
lines = file.readlines()
lines[line_number - 1] = new_line + '\n'
with open(file_path, 'w') as file:
file.writelines(lines)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceLine {
public static void main(String[] args) {
String filePath = "example.txt";
int lineNumber = 3;
String newLine = "This is the new line.";
replaceLine(filePath, lineNumber, newLine);
}
public static void replaceLine(String filePath, int lineNumber, String newLine) {
try (BufferedReader reader = new BufferedReader(new FileReader(filePath));
BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
String line;
int currentLineNumber = 1;
while ((line = reader.readLine()) != null) {
if (currentLineNumber == lineNumber) {
writer.write(newLine);
} else {
writer.write(line);
}
writer.newLine();
currentLineNumber++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
const fs = require('fs');
function replaceLine(filePath, lineNumber, newLine) {
const lines = fs.readFileSync(filePath, 'utf-8').split('\n');
lines[lineNumber - 1] = newLine;
fs.writeFileSync(filePath, lines.join('\n'));
}
在这些示例代码中,我们首先读取文件中的所有行,然后找到要替换的行,并将其替换为新行。最后,我们将修改后的行写回文件中。请注意,这些示例代码仅适用于较小的文件,因为它们会一次性将整个文件读入内存。对于大型文件,您可能需要使用流来逐行读取和写入文件。
领取专属 10元无门槛券
手把手带您无忧上云