Python 如何将文件的每个部分写入单独的目录?
我有一个具有以下结构的文件(名称:Python 如何将文件的每个部分写入单独的目录?,python,file-io,Python,File Io,我有一个具有以下结构的文件(名称:state2): timestep 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 1.2176673 时间步长 -0.0151405 -0.0000000 -0.0874954 -0.0347223 0.0000001 1.2559323 时间步长 -0.0492274 0.0000001 -0.1238961 -0
state2
):
timestep
0.0000000 0.0000000 0.0000000
0.0000000 0.0000000 1.2176673
时间步长
-0.0151405 -0.0000000 -0.0874954
-0.0347223 0.0000001 1.2559323
时间步长
-0.0492274 0.0000001 -0.1238961
-0.0976473 -0.0000002 1.2335932
.... (24个时间步)
我试图将每个timestep
(仅数字)放入目录中的单独文件中。我已经编写了以下代码,但它只将第一个timestep数据写入文件。如果我删除中断
,那么它会将整个原始文件再次写入单独的文件
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
您不需要使用带有
if
和break
骗局的for
嵌套。您需要做的只是:
- 遍历原始文件中的行。
- 当您看到“timestep”时,打开一个要写入的新文件并转到下一行
- 如果看不到“timestep”,请将该行写入当前文件,然后移到下一行
是否每个时间步都有相同的行数?是的,每个时间步都有相同的行数仔细地遍历代码。在范围(0,len(所有_行)内循环i的
时会发生什么
每次?不管怎样,Pranav的答案是正确的。@Sophi,我认为原始输入文件的格式有点混乱。你能确认你的state2
文件看起来像我编辑的吗?也就是说,两行数字之间没有空行?@PranavHosangadi,是的,你的修改是正确的rect.没有空行。请回滚对OP问题的编辑。您已删除state2
文件中行与行之间的换行符…那些可能是有意和部分文件的换行符…(或至少添加换行符)@Yatin,因为OP正在写入所有行[i+1],所有行[i+2]
在他们的原始代码中,两行数据之间没有空行是理所当然的。换行符是在OP没有格式化问题的那一部分时出现的,需要添加两行换行符以获得SO的标记以显示换行符。@PranavHosangadi,我试过你的代码,得到:elif fout不是None:^s错误:无效syntax@PranavHosangadi这本身可能就是OP的代码不起作用的原因…Sophi,你的文件在每个值行之后都有换行符吗…?@PranavHosangadi,没有,它没有空行
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)