python - 在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)
解决方案
问题是 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()
另外,您发布的代码有一些缩进问题,我在这里修复了它们。
推荐阅读
- typescript - TypeScript,扩展全局对象
界面 - android - 导航架构组件导航,只有一个上下文
- python - Google Colab 在包含大量文件的云端硬盘文件夹中遇到问题
- c++ - malloc: *** 对象 0x100519860 的错误:未分配被释放的指针 *** 在 malloc_error_break 中设置断点以进行调试
- java - Kotlin:扩展动态给定的超类型
- android - TextView:获取最后一行末尾的 x 和 y
- python - 将 JSON 数据加载到 pandas 数据框中并创建自定义列
- python - 根据行标签合并行 - pandas python
- python - 如何有效地索引 Groupby 对象?
- yocto - 如何为 yocto systemd 服务添加配方