来自question的后续行动我昨天问了这个问题,这让我发现了一个新问题(太棒了!)。
所以我有这段代码,使用 .strip('()\n') 将 .dat 文件从
然后使用 (34354435.0000007, 623894584.000006)
转换为 34354435.0000007, 623894584.000006
.rstrip('\n')
删除尾随换行符,以便我可以将其导入到 matplotlib 并绘制多边形。代码中的顺序是相反的,但我认为这并不重要,因为无论它位于 for
循环中的哪个位置,这都会带来相同的错误;
lang=js
data_easting=[]
data_northing=[]
#Open the poly.dat file (in Python)
Poly = open('poly.dat','r')
#Loop over each line of poly.dat.
for line in Poly.readlines():
line = line.rstrip('\n')
print (line +'_becomes')
line = line.strip('()\n')
print (line)
x,y = line.split(', ')
data_easting.append(x)
data_northing.append(y)
import numpy
data_easting = numpy.array(Easting,dtype=float)
data_northing = numpy.array(Northing,dtype=float)
from matplotlib import pyplot
我收到值错误
;
16 line = line.strip('()\n')
17 print (line)
---> 18 x,y = line.split(', ')
19 data_easting.append(x)
20 data_northing.append(y)
ValueError: not enough values to unpack (expected 2, got 1)
通过 print
函数,我发现它正在尝试循环遍历底部的换行符(因此,当我尝试在 x 和 y 之间分割数据时,它在换行符处失败,因为换行符只有 1 个值,其中没有定义“,”。
...
(331222.6210000003, 672917.1531000007)_becomes
331222.6210000003, 672917.1531000007
_becomes
-----------------------------------------------
.rstrip
不是应该删除尾随的换行符吗?我还尝试过 .replace
,并在 rstrip
函数中包含 \r
和
,我得到了相同的结果结果。我的代码有什么问题,无法响应 .rstrip
和 .strip
?
或者,如果有一种方法可以在最终数据输入时完全跳过或停止循环,那么我认为这将绕过这个问题。
谢谢
受限的学习者。
最佳答案
删除文件末尾多余的空行。
如果输入中需要额外的空行,您需要检测并忽略它们:
for line in Poly: if line == '\n': continue ...
关于python - 使用 `.rstrip()` 和 `.strip() to remove newline `\n`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64633449/