如何在python中添加for循环?
我正在使用python更改mdp文件夹中原有的文件中的几行,从而从这些文件中创建新文件。我需要对1000个文件执行此操作。有人能推荐一个for循环,它读取所有文件并对其进行更改,然后一次性创建新文件吗 这样,我必须更改路径中后跟'md_'的数字,这很麻烦,因为这里有1000个文件 我尝试使用str(),但出现“无法读取文件错误”如何在python中添加for循环?,python,for-loop,Python,For Loop,我正在使用python更改mdp文件夹中原有的文件中的几行,从而从这些文件中创建新文件。我需要对1000个文件执行此操作。有人能推荐一个for循环,它读取所有文件并对其进行更改,然后一次性创建新文件吗 这样,我必须更改路径中后跟'md_'的数字,这很麻烦,因为这里有1000个文件 我尝试使用str(),但出现“无法读取文件错误” fin = open("/home/abc/xyz/mdp/md_1.mdp", "rt") fout = open("/home/abc/xyz/middle/md
fin = open("/home/abc/xyz/mdp/md_1.mdp", "rt")
fout = open("/home/abc/xyz/middle/md_1.mdp", "wt")
for line in fin:
fout.write(line.replace('integrator = md', 'integrator
= md-vv'))
fin = open("/home/abc/xyz/middle/md_1.mdp", "rt")
fout = open("/home/abc/xyz/mdb/md_1.mdp", "wt")
for line in fin:
fout.write(line.replace('dt = 0.001', 'dt
= -0.001'))
fin.close()
fout.close()
假设要编辑mdp文件夹中的所有文件,可以执行以下操作
import os
dir = "/home/abc/xyz/mdp/"
for filename in os.listdir(dir):
with open(dir + filename, "r+") as file:
text = file.read()
text = text.replace("dt = 0.001", "dt = -0.001")
file.seek(0)
file.write(text)
file.truncate()
这将遍历每个文件,并使用str.replace()对其进行更改
如果mdp文件夹中还有其他文件不想编辑,可以使用和If语句检查文件名是否正确。添加类似这样的内容来封装WITHOPEN语句
if filename.startswith("md_")
os.listdir(path)
是您的朋友:
import os
sourcedir = "/home/abc/xyz/mdp"
destdir = "/home/abc/xyz/middle"
for filename in os.listdir(sourcedir):
if not filename.endswith(".mdp"):
continue
source = os.path.join(sourcedir, filename)
dest = os.path.join(destdir, filename)
# with open(xxx) as varname makes sure the file(s)
# will be closed whatever happens in the 'with' block
# NB text mode is the default, and so is read mode
with open(source) as fin, open(dest, "w") as fout:
# python files are iterable... avoids reading
# the whole file in memory at once
for line in fin:
# will only work for those exact strings,
# you may want to use regexps if number of
# whitespaces vary etc
line = line.replace("dt = 0.001", "dt = -0.001")
line = line.replace(
'integrator = md',
'integrator = md-vv'
)
fout.write(line)
请向我们展示您尝试过的代码,以便我们更好地评估出错的地方,而不是猜测您可能写了什么。请修复代码缩进,并尽一切努力,学会正确关闭文件。@DragonThinks,我已经编写了我尝试过的代码。当我试图一次在一个文件中进行更改时,这种方法是有效的。我有1000个这样的文件,我想知道它是如何一次完成的。就地覆盖文件是不安全的——如果出现任何问题,您将丢失原始数据。最好先写入临时文件,然后用新文件替换原始文件。另外,在内存中读取整个文件会导致MemoryError,最好是逐行操作(文件是可写的)。还要注意,在OP的示例中,处理过的文件实际上被写入了另一个目录…我尝试了这个方法,但它说:dest.write(line)AttributeError:'str'对象没有属性'write',确实有一个输入错误,当然应该是
fout.write()
,但是你应该能够通过阅读错误消息、回溯和源代码来解决这类错误(如果你希望进行任何编码,就需要学习调试)。顺便说一句,还有另一个输入错误(对于源代码中的行
而不是对于fin中的行
)-这两个都是固定的。如果我在fin中给出一个文件名,它会对所有1000个文件运行吗?我无法理解我应该在fin中写什么作为开放(源代码)对不起,但是你的问题没有意义。fin
是一个文件
对象,通过调用打开获得(source)
,其中source
是文件的绝对路径,根据sourcedir
的值和filename
的值构建。此代码将迭代sourcedir
中的所有文件,跳过没有.mdp扩展名的文件,并处理有扩展名的文件,并且它将工作(至少理论上是这样)无论在sourcedir
中有多少.mdp文件。