DM71
DM71

Reputation: 77

newline character problems with Python (strip)

If I write

f = open("file.csv","r")
    if f.mode == "r":
        cols = []
        snames = []
        svals = []
        rows = f.readlines()
        for x in rows:
            x.strip("\n")
            cols = x.split(",")
            snames.append(cols[0])
            svals.append(cols[1])

then svals still has the \n characters I dont want e.g. '20.43256639\n'

but if I do this instead, then svals shows the correct values without the \n

for x in rows:
    cols = x.split(",")
    snames.append(cols[0])
    svals.append(cols[1].strip("\n"))

svals DOES have the right values e.g. '20.43256639'

Upvotes: 1

Views: 63

Answers (1)

AKX
AKX

Reputation: 169298

x.strip("\n")

doesn't modify x in-place (since strings are immutable anyway). Try

x = x.strip("\n")

instead, or to put it all a little more succinctly:

with open("file.csv","r") as f:
    snames = []
    svals = []
    for x in f:
        sname, sval = x.strip().split(",", 1)
        snames.append(sname)
        svals.append(sval)

Upvotes: 2

Related Questions