如何为每个括起来的方括号保存新的.txt 文件?

问题描述 投票:0回答:1

所以我计划将每个多边形保存到单独的 .txt 文件中,但问题是有 4,000 多个多边形,手动完成它需要几个小时甚至几天才能完成。

有没有办法自动完成,例如使用Python?

每个多边形将具有以下格式:

[
"8.782897907000063,1.718493196000054",
"8.782768250000061,1.718278646000044",
"8.78276825100005,1.718376662000026",
"8.78288150700007,1.718478835000042",
"8.782897907000063,1.718493196000054"
]

因此当前文件将类似于以下内容:

[
"8.782897907000063,1.718493196000054",
"8.782768250000061,1.718278646000044",
"8.78276825100005,1.718376662000026"
]
[
"8.78288150700007,1.718478835000042",
"8.782897907000063,1.718493196000054",
"8.782897907000063,1.718493196000054"
]
[
"8.78288150700007,1.718478835000042",
"8.782897907000063,1.718493196000054",
"8.782897907000063,1.718493196000054"
]

因此每个文件都会有方括号和方括号括起来的数据/坐标。

如何为上述每种格式保存新文件?

谢谢!

python notepad++ notepad
1个回答
0
投票

我不确定你的问题。我假设您在单个文件中有一个多边形位置列表。您希望它们均匀地分布在新文件中。你正在要求自动化。为此,我编写了一个代码块。

注意:首先使用示例数据进行测试,然后尝试使用原始文件,否则您将面临创建多个文件的风险,这些文件可能会降低系统速度。

import ast  

MAX_LIMIT = 3 # Count of Data that should be persisted to a file

file_data = open("data.txt", "r") # name of the file with a big list
data = ast.literal_eval(file_data.read())
file_data.close()


old_count = 0
count = MAX_LIMIT
index = 0
last_value_accessed = False
while True:
    if (count > len(data)):
        break
    sliced_arr = data[old_count:count:]
    new_file = open("new_file_"+str(index)+".txt", "w")
    new_file.write(str(sliced_arr))
    new_file.close()

    index+=1
    old_count = count
    count+=MAX_LIMIT
    if (count > len(data) and count != len(data) - 1 and not last_value_accessed):
        count = len(data) - 1
        last_value_accessed = True
© www.soinside.com 2019 - 2024. All rights reserved.