【发布时间】:2021-02-15 08:28:13
【问题描述】:
我在 Python 脚本中有以下逻辑:
def importAndAnalyze(rowLimit = 3):
layerProperties = iface.addVectorLayer("Downloads/parcels-shp/parcels.shp", "Parcels", "ogr")
if not layerProperties:
print("layerProperties failed to load!")
layerEntrances = iface.addVectorLayer("Downloads/Metro_Stations-shp/Metro_Stations.shp", "Metro_Stations", "ogr")
if not layerEntrances:
print("layerEntrances failed to load!")
features = layerProperties.getFeatures()
counter = 0
featuresSelected = []
Path('Desktop/output.csv').touch()
with open('Desktop/output.csv', 'w') as csvfile:
csvWriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
csvWriter.writerow(['Tooltip', 'Lat','Lon', 'Distance'])
for feature in features:
if counter < rowLimit:
csvWriter.writerow([feature['TOOLTIP'], feature.geometry().centroid().asPoint().y(),feature.geometry().centroid().asPoint().x(), Ranker.calculateDistance(feature, layerEntrances)])
if counter % 100 == 0:
csvfile.flush()
else:
break
counter += 1
Ranker.importAndAnalyze(1000000)
当我输入 800,000 行信息并将 rowLimit 变量设置为 100 万行时,它当前恰好将 65,535 行保存到 output.csv 文件中,然后停止保存新行,即使脚本继续运行数小时也是如此。
如何让我的脚本保存其他 734,465 行?
===
编辑:在 cmets/answers 中有很多关于我的 rowLimit 变量是否实际设置为一百万的正确猜测。所以我添加了更多代码来显示它是如何运行的上下文。
【问题讨论】:
-
如果
rowlimit的目的是限制文件的大小,那么您的代码应该在到达for循环时将break排除在外,而不是无休止地循环通过features并且对它检索到的内容不做任何事情。 -
您的 csv 文件打开上下文中的
w选项可能是问题所在。将其更改为a以附加数据。 -
@BoarGules 谢谢,这是关于打破循环的好建议。我已经编辑了代码示例以遵守该建议。
-
Python 不会阻止您编写任意数量的行。你确定你有超过 65536 行吗?你确定
rowLimit是1000000吗?你确定你的counter开始一个0吗?你确定这部分代码是罪魁祸首吗?你能证明吗? -
Python 中没有限制拒绝 65535 行之后的内容。请edit您的问题提供minimal reproducible example。