用python删除文件中的行的更好方法?

问题描述

| 我想删除文件中的一行;目前,我正在创建一个新文件,复制除要删除的行之外的每一行,删除旧文件,并将新文件重命名为与旧文件相同的文件名。是否有删除线的更好方法?
f = open(\'./todo.txt\',\'r\')
newF = open(\'./todo-run.txt\',\'a\')
lines = f.readlines()
cLine = lines[int(index) - 1]

for line in lines:
  if line != cLine:
    newF.write(line)
f.close()
newF.close()
os.remove(\'./todo.txt\')
shutil.move(\'./todo-run.txt\',\'./todo.txt\')
    

解决方法

sed中的解决方案,您可以使用\“ subprocess \”来调用。例如,要删除第18行,请执行以下操作:
sed -i \'18 d\' filename
    ,哪种方式更好?例如,您可以将文件内的数据混洗,然后使用更少的内存但进行更多的查找来截断它(尤其是如果您将其改编为不在一个块中读取后一部分的话):
def cutfile(file,startcut,endcut):
  file.seek(endcut)
  dataafter=file.read()
  file.seek(startcut)
  file.write(dataafter)
  file.truncate()
或者,您无法在重命名之前删除旧文件以获取原子更新。这确实取决于您的目标。     ,它并没有比您的好很多,但是(由于您的文件似乎适合主内存),您可以尝试以下操作:
f = open(filepath,\'r\')
lines = [line.rstrip(\'\\n\') for line in f if not <CONDITION>]
f.close()
f.open(\'filepath,\'w\')
f.write(\'\\n\'.join(lines))
f.close()
    ,您可以通过一次覆盖一个来移动不需要的行之后的行。虽然没有比您目前正在做的更好。如果文件不以换行符结尾,则此代码会有点有趣。我在Win7 64位Python 2.7上进行了测试。 move_lines.py:
f = open(\'todo.txt\',\'r+\')
line_index = 0
prev_line_head = 0
remove_line_index = 3
move_lines = False
while True:
  line_head = f.tell()
  line = f.readline()

  if line == \'\': #EOF
    f.seek(prev_line_head)
    f.truncate()
    break

  if move_lines:
    f.seek(prev_line_head)
    f.write(line)
    f.flush()
    line_head = f.tell()
    line = f.readline() # read past the line we already read to start this iteration
  elif line_index == remove_line_index:
    move_lines = True
  prev_line_head = line_head
  line_index += 1
f.close()
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...