在Python中使用writelines向文件中添加一行也会在不同位置复制行?

在Python中使用writelines向文件中添加一行也会在不同位置复制行?,python,file,Python,File,我试图将一个文件复制到一个新文件夹中,然后在新文件中写入一行。我想在一个循环中创建多个文件夹,每个文件夹都有一行不同的文件。要做到这一点,我正在使用 import numpy as np import os import subprocess # Name of the file Exec = 'examplefile.py' # List of parameters to be looped deltax = np.array([2., 1. ,0.5, 0.1]) for stepsi

我试图将一个文件复制到一个新文件夹中,然后在新文件中写入一行。我想在一个循环中创建多个文件夹,每个文件夹都有一行不同的文件。要做到这一点,我正在使用

import numpy as np
import os
import subprocess


# Name of the file
Exec = 'examplefile.py'
# List of parameters to be looped
deltax = np.array([2., 1. ,0.5, 0.1])

for stepsize in deltax:
    #Step1: Specify path and make directory for the parameter
    DirPath = str(stepsize)+'Debye'
    if not os.path.exists(DirPath):
        os.makedirs(DirPath)
    
    #Step2: Copy input file into the new folder
    bashCopy = 'cp ' + Exec + ' ./' + DirPath + '/'
    process1 = subprocess.Popen(bashCopy, shell=True)
    process1.wait()

    #Step3: add line at correct position
    namelist_path = DirPath + '/' + Exec
    with open(namelist_path, 'r+') as file:
        lines = file.readlines()
        lines.insert(110, "string including stepsize")
        file.seek(0,0)
        file.writelines(lines)
该程序似乎可以正确地创建文件夹、复制文件和写入行。但是,由于某种原因,它还会获取第209行第26列之后的所有内容,并将其复制到文件的末尾。 examplefile.py文件的结尾应该是什么样子:

DiagTrackParticles(
    species = "ions",
    every = [timetostep(tacc/reft), timetostep(tacc/reft), 0.],
    attributes = ["x", "px", "py", "pz", "w"]
)
它看起来像什么:

DiagTrackParticles(
    species = "ions",
    every = [timetostep(tacc/reft), timetostep(tacc/reft), 0.],
    attributes = ["x", "px", "py", "pz", "w"]
)acc/reft), timetostep(tacc/reft), 0.],
    attributes = ["x", "px", "py", "pz", "w"]
)
有人知道为什么会这样吗?当我在Spyder中逐行运行代码的编写部分时,它工作正常