简体   繁体   中英

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

A follow up from a question I asked yesterday that allowed me to identify a new problem (How wonderful!). So I have this code that is converting a .dat file from (34354435.0000007, 623894584.000006) to 34354435.0000007, 623894584.000006 with .strip('()\\n') and then removing a trailing newline with .rstrip('\\n') so I can import it to matplotlib and plot a polygon. The order in the code is the other way around, but I don't think it matters as this brings up the same error regardless of where it is in the for loop;

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

I get a 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)

And through the print function I've figured out it's trying to loop through the newline at the bottom (so when I try to split the data across x and y, it fails at the newline because the newline only has 1 value with no ", " defined in it.

...
(331222.6210000003, 672917.1531000007)_becomes
331222.6210000003, 672917.1531000007
_becomes

-----------------------------------------------

Isn't .rstrip supposed to remove the trailing newlines? I've also tried .replace , and including \\r and in the rstrip function and I get the same result. What is wrong with my code that it won't respond to the .rstrip and .strip ?

Alternatively, if there's a way to outright skip or stop the loop at the final data entry, that would bypass the problem I think.

Thanks,

A constricted learner.

  • Remove the extra blank line from the end of the file.

  • If extra blank lines are to be expected in the input, you'll need to detect and ignore them:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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