【问题标题】:Using `.rstrip()` and `.strip() to remove newline `\n`使用 `.rstrip()` 和 `.strip() 删除换行符 `\n`
【发布时间】:2021-02-14 09:29:58
【问题描述】:

我昨天问的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

我收到了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 有什么问题?

或者,如果有办法在最终数据输入时彻底跳过或停止循环,那将绕过我认为的问题。

谢谢,

一个受限的学习者。

【问题讨论】:

  • 文件末尾有空行吗?
  • 是的,我用记事本++ 搜索了代码丢失的任何内容,最后一行是空格(通过使用 ctrl-f 并搜索“\n”找到)。当我尝试使用 .rstrip()rstrip(' ')rstrip('\n') 删除它时,仍然会出现相同的 Value Error
  • strip 确实删除了'\n',但现在您的line 只是一个空字符串-''。所以你基本上是在尝试做x, y = ''.split(', '),这将给出完全相同的错误......
  • 主题:看看How to read a file without newlines?。相关:在您的代码示例中,您打开了一个文件对象,但您从未close() 它。最好使用with 语句。
  • 谢谢 Tomerikoo 和 Fuppes 先生,你们都解释了哪里出了问题,以及我可以用我的代码做得更好的地方。我会用那个链接来复习!

标签: python python-3.x newline strip


【解决方案1】:
  • 删除文件末尾多余的空行。

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

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

【讨论】:

  • 编辑:这完全解决了我的问题,我现在明白我错过了什么。谢谢!
猜你喜欢
  • 2011-07-01
  • 2019-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-29
  • 2011-01-08
  • 2012-08-12
相关资源
最近更新 更多