python - 如何将文件的每个部分写入单独的目录中?
问题描述
我有一个state2
具有以下结构的文件(名称:):
timestep
0.0000000 0.0000000 0.0000000
0.0000000 0.0000000 1.2176673
timestep
-0.0151405 -0.0000000 -0.0874954
-0.0347223 0.0000001 1.2559323
timestep
-0.0492274 0.0000001 -0.1238961
-0.0976473 -0.0000002 1.2335932
.... (24 timesteps)
我试图将每个timestep
(仅数字)放在目录中的单独文件中。我编写了以下代码,但它只将第一个时间步长数据写入文件。如果我删除break
,那么它会将整个原始文件再次写入单独的文件中。
import os
steps = []
BaseDir=os.getcwd()
data=os.path.join(BaseDir, 'state2')
f= open(data, 'r')
all_lines = f.readlines()
for k in range(24):
path = os.path.join(BaseDir, 'steps_{0:01d}'.format(k))
os.mkdir(path)
dest = os.path.join(BaseDir,'steps_{0:01d}'.format(k), 'step{0:01d}'.format(k))
fout = open(dest, 'w')
for i in range(0, len(all_lines)):
if 'timestep' in all_lines[i]:
fout.write('{0}{1}}'.format(all_lines[i+1], all_lines[i+2]))
break
解决方案
你不需要嵌套for
的if
和break
恶作剧。您需要做的就是:
- 遍历原始文件中的行。
- 当您看到“timestep”时,打开一个要写入的新文件并移至下一行。
- 如果您没有看到“timestep”,则将该行写入当前文件并移至下一行。
fout = None
timestepnum = 0
for line in all_lines:
if line == "timestep": # Or whatever condition you identify
# this line says timestep, so we have now started looking at a new timestep (condition 1)
if fout is not None:
fout.close() # close the old timestep's file if it is already open
timestepnum += 1
# make the directory
path = os.path.join(BaseDir, 'steps_{0:01d}'.format(timestepnum))
os.mkdir(path)
# open the file
filename = os.path.join(BaseDir, f"steps_{timestepnum:01d}", f"step{timestepnum:01d}") # Code to specify file name
fout = open(filename, 'w')
elif fout is not None:
# Condition 2 -- write this line as-is to the file.
fout.write(line)
推荐阅读
- exception - 如何找到 RAVENDB 方法可能引发的异常?
- python - 每分钟检查一次是否生成了 *.odb 文件。如果是 --> 获取数据
- intellij-idea - 如何生成 IntelliJ JUnit json 自动报告?
- node.js - 执行 Python 脚本的 Express 路由上的 Heroku H12 请求超时错误
- deep-learning - 卷积网络和卷积层有什么区别?
- typescript - 可能未定义的输出值
- java - Selenium ChromeDriver:增加获取 WebElement 文本的时间
- eclipse - 方法调用链后的缩进
- r - 将文件名添加到数据框列表
- elasticsearch - 我在哪里放置索引。*弹性搜索集群中的设置