Skip to main content
 首页 » 编程设计

python之读取后从文本文件中删除行

2025年05月04日7zhwl

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

123456 
011111 
02222 
03333 

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

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 时,我希望它从文件中删除,所以当我再次使用该程序时,从第二个数字继续。

对代码有任何想法吗?

请您参考如下方法:

我想写这个作为评论,但我没有必要的要点 这样做,所以我只写一个答案。添加 Darren Ringer 的回答。

阅读该行后,您可以关闭文件并再次打开它覆盖 除了要删除的行外,它包含旧内容, 已经在这个答案中描述过:

Deleting a specific line in a file (python)

另一种选择是使用相同文件名的就地过滤 对于您的输出,它将用过滤后的内容替换您的旧文件。这 本质上是一样的。您只是不必再次打开和关闭文件。 1_CR 也已经回答了这个问题在下面的问题中也可以 可在 https://docs.python.org/ 找到( Optional in-place filtering section ):

Deleting a line from a text file

根据您的情况进行调整,它看起来像这样:

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 

干杯