可以使用以下步骤:
下面是一些常见的编程语言的文件操作函数和方法的示例:
with open('file.txt', 'r+') as file:
lines = file.readlines()
file.seek(0)
file.write(''.join(lines[-3:]))
file.seek(0, 2)
file.truncate()
推荐的腾讯云相关产品:云服务器(ECS),产品介绍链接:https://cloud.tencent.com/product/cvm
import java.io.*;
public class FileManipulation {
public static void main(String[] args) {
try {
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
StringBuilder content = new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
reader.close();
int lastLinesToKeep = 3;
String[] lines = content.toString().split("\n");
StringBuilder newContent = new StringBuilder();
for (int i = Math.max(lines.length - lastLinesToKeep, 0); i < lines.length; i++) {
newContent.append(lines[i]).append("\n");
}
newContent.append(content);
FileWriter writer = new FileWriter(file);
writer.write(newContent.toString());
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
推荐的腾讯云相关产品:云服务器CVM,产品介绍链接:https://cloud.tencent.com/product/cvm
const fs = require('fs');
fs.readFile('file.txt', 'utf8', function (err, data) {
if (err) {
console.error(err);
return;
}
const lines = data.split('\n');
const lastLines = lines.slice(-3);
const newContent = lastLines.join('\n') + '\n' + data;
fs.writeFile('file.txt', newContent, function (err) {
if (err) {
console.error(err);
return;
}
console.log('File modified successfully.');
});
});
推荐的腾讯云相关产品:云服务器CVM,产品介绍链接:https://cloud.tencent.com/product/cvm
这种操作适用于需要在文件内容的开头添加最后几行的情况,例如日志文件的滚动和维护等场景。
领取专属 10元无门槛券
手把手带您无忧上云