首页 > 解决方案 > 在python中运行for循环

问题描述

我正在尝试从名为“mdp”的文件夹中已有的 1000 个文件生成 1000 个新文件到一个新文件夹“mdb”中,更改每个原始 1000 个文件中的几行。我从溢出中获得了一些帮助,@bruno desthuilliers 建议我使用这个特定的代码,但它还没有工作,它说 dest.write(line) AttributeError: 'str' object has no attribute 'write'。我对编程有点陌生。谁能告诉我我错过了什么?

     import os
     sourcedir = "/home/abc/xyz/mdp/"
     destdir = "/home/abc/xyz/mdb/"

     for filename in os.listdir(sourcedir):
       if not filename.endswith(".mdp"):
       continue

       source = os.path.join(sourcedir, filename)
       dest = os.path.join(destdir, filename)

     fin = open("/home/abc/xyz/mdp/md_1.mdp")
     fout = open("/home/abc/xyz/mdb/md_1.mdp", "w")
     for line in source:
     line = line.replace('integrator               = md', 'integrator               = md-vv')
     line = line.replace('dt                       = 0.001', 'dt                      = 
    -0.001')
     dest.write(line)

标签: pythonfor-loop

解决方案


问题是 dest 是一个字符串,而不是打开文件的实例。我修改的代码应该可以工作。请试一试,让我知道它是怎么回事!

import os

sourcedir = "/home/abc/xyz/mdp/"
destdir = "/home/abc/xyz/mdb/"

for filename in os.listdir(sourcedir):
    if not filename.endswith(".mdp"):
        continue

    # Gets the fullpath for the source and dest files
    source = os.path.join(sourcedir, filename)
    dest = os.path.join(destdir, filename)

    # Open the files in read and write mode
    fin = open(source,"r")
    fout = open(dest, "w")

    # Creates a list of the lines contained in the 'dest' file
    lines = fin.readlines()

    # Close the source file as is no longer needed
    fin.close()

    # Loop over each line to implement the modifications
    for line in lines:
        line = line.replace('integrator               = md', 'integrator               = md-vv')
        line = line.replace('dt                       = 0.001', 'dt                      = 
    -0.001')
        # Writes the replaced line into the 'dest' file
        fout.write(line)

    # Close the 'dest' file after finishing looping
    fout.close()

另外,您发布的代码有一些缩进问题,我在这里修复了它们。


推荐阅读