python - 使用 `.rstrip()` 和 `.strip() to remove newline `\n`

标签 python python-3.x newline strip

来自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/

相关文章:

c - 每次我从 C 中的输入文件读取 '\n' 时都无法循环函数

python - Geopandas:无法更改 geopandas 对象的 crs

python - 将一列添加到表 django

python - 如何将自定义数组添加到 paraview 中的多数据?

python - 在 Django 模型中,外键字段如何知道与其他模型中的哪个字段匹配?

bash - echo 换行符输出

python - 更改 Holoviews 热图中的刻度线标记时间段

python - 当为变量定义内置函数时,del 对内置函数做了什么?

python - python 中的 Pandas 数据框 : Removing rows from df1 based on rows in df2

c++ - 如何检查 ifstream 文件末尾是否有新行。 (c++)