阅读后从文本文件中删除行 [英] Remove line from a text file after read

查看:102
本文介绍了阅读后从文本文件中删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为1.txt的文本文件,其中包含以下内容:

I have a text file named 1.txt which contains the following:

123456
011111
02222
03333

并且我创建了一个python代码,该代码将第一行复制到x个文件夹中,复制到文件number.txt中 然后将第二个复制到x个文件夹:

and I have created a python code which copy the first line to x number of folders to file number.txt then copy the second to x number of folders:

progs = int(raw_input( "Folders Number : "))
with open('1.txt', 'r') as f:
    progs2 = f.read().splitlines()
progs3 = int(raw_input( "Copy time for each line : "))
for i in xrange(progs):
    splis = int(math.ceil(float(progs)/len(progs3)))
    with open("{0}/number.txt".format(pathname),'w') as fi:
        fi.write(progs2[i/splis])

我想编辑代码以将其复制到指定数量的文件夹后删除该行; 例如,当代码复制数字123456时,我希望将其从文件中删除,因此当我再次使用该程序以从第二个数字继续时.

I want to edit the code to remove the line after copying it to the specified number of folder; like when the code copy the number 123456 I want it to be deleted from the file so when I use the program again to continue from the second number.

对代码有任何想法吗?

推荐答案

我想将此内容写为注释,但我没有必要的要点 为此,我只写一个答案.加上达伦·林格的答案.

I'd like to write this as a comment but I do not have the necessary points to do that so I'll just write an answer. Adding up on Darren Ringer's answer.

读完该行后,您可以关闭文件并再次打开将其覆盖 它具有旧内容,但要删除的行除外, 该答案中已经对此进行了描述:

After reading the line you could close the file and open it again overwriting it with the old content except for the the line which you want to remove, which has already been described in this answer:

删除文件中的特定行(python)

另一个选择是使用相同文件名进行就地过滤 为您的输出,它将使用过滤后的内容替换您的旧文件.这 基本相同.您只是不必再次打开和关闭文件. 1_CR 在以下问题中也已经回答了这个问题,也可以 可以在 https://docs.python.org/(

Another option would be to use in-place Filtering using the same filename for your output which would replace your old file with the filtered content. This is essentially the same. You just don't have to open and close the file again. This has also already been answered by 1_CR in the following question and can also be found at https://docs.python.org/ (Optional in-place filtering section):

从文本文件中删除一行

适合您的情况,看起来像这样:

Adapted to your case it would look something like this:

import fileinput
import sys, os

os.chdir('/Path/to/your/file')

for line_number, line in enumerate(fileinput.input('1.txt', inplace=1)):
  if line_number == 0:
    # do something with the line
  else:
    sys.stdout.write(line) # Write the remaining lines back to your file

欢呼

这篇关于阅读后从文本文件中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆