繁体   English   中英

使用 `.rstrip()` 和 `.strip() 删除换行符 `\\n`

[英]Using `.rstrip()` and `.strip() to remove newline `\n`

我昨天提出的一个问题的跟进,让我发现了一个新问题(太棒了!)。 所以,我有这样的代码是从转换.dat文件(34354435.0000007, 623894584.000006)34354435.0000007, 623894584.000006.strip('()\\n')然后除去与尾随换行符.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 ,包括\\r rstrip函数中,我得到了相同的结果。 我的代码不响应.rstrip.strip什么问题?

或者,如果有一种方法可以在最终数据输入处完全跳过或停止循环,那将绕过我认为的问题。

谢谢,

一个受限的学习者。

  • 从文件末尾删除多余的空行。

  • 如果在输入中需要额外的空行,您需要检测并忽略它们:

     for line in Poly: if line == '\\n': continue ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM