1

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'

DM71
  • 77
  • 1
  • 8
  • The line `x.strip("\n")` have no effect. You probably wanted to do `x = x.strip("\n")`. By the way whitespaces are already the default, so just do `x = x.strip()` – Tomerikoo Nov 18 '20 at 12:43
  • @Tomerikoo `'\n'` is _not_ the default. The default is all whitespace. – AKX Nov 18 '20 at 12:44
  • Does this answer your question? [Python .strip method not working](https://stackoverflow.com/questions/40444787/python-strip-method-not-working) – Tomerikoo Nov 18 '20 at 12:46
  • You're not wrong, but `x.strip()` vs `x.strip("\n")` vs `x.rstrip()` certainly makes a difference if you're reading data where indentation matters (such as, oh, say, Python). – AKX Nov 18 '20 at 12:46

1 Answers1

2
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)

AKX
  • 152,115
  • 15
  • 115
  • 172