Python 在文本文件中的某些字符串之间写入数据(最后一个元素错误)
所以我有几个.txt文件,每个文件中有超过500.000行。 在所有这些文件中,我都有一个部分,我想将其解压缩到自己的.txt文件中 为此,我使用以下代码:Python 在文本文件中的某些字符串之间写入数据(最后一个元素错误),python,Python,所以我有几个.txt文件,每个文件中有超过500.000行。 在所有这些文件中,我都有一个部分,我想将其解压缩到自己的.txt文件中 为此,我使用以下代码: for i, structure in enumerate(structures): with open("data.txt", 'r') as f: structure_data = open('data_new.txt'), 'w') copy = False for line i
for i, structure in enumerate(structures):
with open("data.txt", 'r') as f:
structure_data = open('data_new.txt'), 'w')
copy = False
for line in f:
if line.strip() == "Structure: {}".format(structures[i]):
structure_data.write(line)
copy = True
elif line.strip() == "Structure: {}".format(structures[i+1]):
copy = False
elif copy:
structure_data.write(line)
structure_data.close()
f.close()
这里是一个结构列表,是的,我有一些结构
所以基本上在每个.txt文件中都有一行写着结构:。现在我想提取数据文件中两个字符串结构[I]和结构[I+1]之间的数据。在我上面的例子中,它就是这样做的,我得到了新的.txt文件和我想要的数据,但是,当我到达.txt文件的末尾时,我得到了以下错误:
elif line.strip() == "Structure: {}".format(structures[i+1]):
IndexError: list index out of range
据我所知,这是因为对于.txt文件的最后一部分,没有结束结构:因此它不能设置copy=False
因此,我确实得到了我想要的.txt文件输出,但正如您所知,没有比代码出错更糟糕的了。那么有没有办法告诉它,如果没有这样的终点线,那么一切都会好起来
更新:
这就是data.txt中的数据可能的样子:
Structure: TR
Dose [cGy] Ratio of Total Structure Volume [%]
0 100
0.100619 100
0.201238 100
0.301857 100
0.402476 100
0.503096 100
0.603715 100
0.704334 100
0.804953 100
0.905572 100
Structure: SV
Dose [cGy] Ratio of Total Structure Volume [%]
0 100
0.100619 100
0.201238 100
0.301857 100
0.402476 100
0.503096 100
0.603715 100
0.704334 100
0.804953 100
0.905572 100
Structure: DY
Dose [cGy] Ratio of Total Structure Volume [%]
0 100
0.100619 88.2441
0.201238 76.4882
0.301857 64.7324
0.402476 52.9765
0.503096 41.2206
0.603715 29.4647
0.704334 17.707
0.804953 17.6784
0.905572 17.6499
所以在结构列表中,我已经有了结构,在这个例子中是TR,SV和DY
因此,在f循环中的for行中,我想在Structures:Structures[I]行和Structures:Structures[I+1]之间获取文本/数据,并将其保存到一个文本文件中,然后执行该操作,直到Structures列表循环通过。但是如上所述,当我到达最后一部分时,没有结束结构:结构[I+1],因此我得到一个错误。这个错误正是我试图避免的。一个简单的解决方案是在文件中任何地方都没有出现的结构的末尾添加一个虚拟结构。 然后可以这样编写循环:
for structure1, structure2 in zip(structures[:-1], structures[1:]):
这将在所有连续结构对上循环
避免使用虚拟结构的另一个解决方案是更换
elif line.strip() == "Structure: {}".format(structures[i+1]):
for i, structure in enumerate(structures):
与
如果第一部分为false,则不会评估导致错误的条件的第二部分。如果决定使用此版本,则可能需要替换
elif line.strip() == "Structure: {}".format(structures[i+1]):
for i, structure in enumerate(structures):
与
因为您实际上并没有在任何地方使用变量结构。您能提供一些示例输入和输出吗?我读了好几遍,我不确定我是否理解你的意图。2秒后会出现……这会删除错误是的,但不会在最后一个结构和没有第二个结构的结尾之间提取文本/数据…@DenverDang抱歉,我错过了。看到更新,我希望这一次它是你想要的:虚拟的东西非常好,也许是最简单的方法,imho:它现在起作用了。非常感谢。