1

I want to keep the file names without the.csv extension, but using rstrip('.csv') deletes the last letter in the strings ending in s:

data_files = [
    "ap_2010.csv",
    "class_size.csv",
    "demographics.csv",
    "graduation.csv",
    "hs_directory.csv",
    "sat_results.csv"
]

data_names = [name.rstrip('.csv') for name in data_files]

I get this results:

["ap_2010", "class_size", "demographic","graduation","hs_directory", "sat_result"]

The end s of strings demographics and sat_results has been removed, why does this happen??

  • From the docs for `rstrip()`: *"Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on."* – pault Apr 19 '18 at 20:27
  • 3
    `.rstrip('.csv')` means to remove as many of the four characters `.`, `c`, `s`, and `v` as possible from the end of the string. – jasonharper Apr 19 '18 at 20:27

2 Answers2

3

This is because rstrip() strips all characters separately from the end of your string.

>>> 'abcdxyx'.rstrip('yx')
'abcd'

This will search for y and x to strip from the right side of your string. If you like to remove the .csv you can use split instead.

>>> "ap_2010.csv".split('.')[0]
"ap_2010"

Also for Filenames it is good practice to use the function os.path.splitext:

>>> import os
>>> os.path.splitext('ap_2010.csv')[0]
"ap_2010"
MrLeeh
  • 5,321
  • 6
  • 33
  • 51
-1

You can get your intended output with this:

data_files = [
    "ap_2010.csv",
    "class_size.csv",
    "demographics.csv",
    "graduation.csv",
    "hs_directory.csv",
    "sat_results.csv"
]

data_names = [name.replace('.csv','') for name in data_files]
NBlaine
  • 493
  • 2
  • 11
  • 1
    What if one of the files is named `"some.csv.something.csv.csv"`? – pault Apr 19 '18 at 20:29
  • In that case, all of the `.csv` would be removed, but I'm not totally convinced that is relevant to what the OP is asking here :) – NBlaine Apr 19 '18 at 20:37