我创建了以下代码来查找文件中的行数,但是我不知道如何删除特定的行号。我是新来的python – 所以如果有一个更简单的方法 – 请告诉我。
file = open("file")
except IOError:
print "Failed to read file."
countLines = len(file.readlines())
我用各种各样的答案找出来:大多数草莓和我在网上看到的东西(对不起,我找不到链接)。
#!/usr/bin/env python
import os, sys
readFile = open("file")
lines = readFile.readlines()
readFile.close()
w = open("file",'w')
w.writelines([item for item in lines[:-1]])
w.close()
如何用python删除文件的最后一行?输入文件示例:helloworldfoobar输出文件示例:helloworldfoo我创建了以下代码来查找文件中的行数,但是我不知道如何删除特定的行号。我是新来的python – 所以如果有一个更简单的方法 – 请告诉我。try:file = open("file")except IOError:print "Failed to read file."cou...
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(12).reshape(3,4), columns=['A', 'B', 'C', 'D'])
print("df",df)
# df.drop([-1],inplace=True)
df.drop([len(df)-1],inplace=True)
print...
这里写自定义目录标题欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变
文本
的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居
中
、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入
欢迎使用Markdown编辑器
你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Mar
打开
文件
后逐行读取同时记录指针位置,由于读取完
一行
后指针位于行尾,所以在读取完
最后
一行
后需要将指针移到上
一行
末尾然后调用f.truncate()。为存储倒数第二行末尾的位置,我们需要一个1 ×\times× 2的数组存储
文件
指针位置:
# 打开
文件
,由于只有二进制模式才支持移动指针操作,所以第二个参数要有'b'。
f = open('test.txt', 'rb+')
line = ...
lines = file.readlines()
del lines[-1] #
删除
最后
一行
del lines[0:16] #
删除
第1行到第17行
file.close()
file_new = open('test.txt','w')
file_new.writelines(lines) # 将
删除
行后的数据写入
文件
file_new.close()
# 按行读入,
删除
最后
一行
file_old = open('example.txt', 'r', encoding="utf-8")
lines = [i for i in file_old]
del lines[-1]
file_old.close()
# 再覆盖写入
file_new = open('example.txt', 'w', encoding="utf-8")
file_new ...
def delLastLine('D:\\data.json'):
with open(path, "rb+") as f:
lines = f.readlines() # 读取所有行
last_line = lines[-1] # 取
最后
一行
for i in range(len(last_line) + 2):
f.seek(-1, os.SEEK_E