使用 `.rstrip()` 和 `.strip() 删除换行符 `\n`
Using `.rstrip()` and `.strip() to remove newline `\n`
我昨天问的 的跟进让我发现了一个新问题(太棒了!)。
所以我有这段代码,它使用 .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
我得到一个 Value Error
;
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
...
我昨天问的 .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
我得到一个 Value Error
;
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 ...