Python Forum
Removing leading\trailing spaces
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Removing leading\trailing spaces
#6
The last bit of code worked a treat on a csv file. The only problem was that it got rid of leading\trailing spaces in the data. I only want the leading\trailing spaces in the first line removed. I tried the following, with my limited knowledge of Python: -

delim = ","
x=0

with open("filtered_csv.csv", "r") as file:
    lines = [map(str.strip, line.split(delim)) for line in file]

with open("filtered_csv.csv", "w") as file:
        for line in lines:
            if x==0:
                file.write(",".join(line) + "\n")
                x=x+1
But all it did was to remove all the data and left only the header. I guess I need to do something different on the str.strip line but don't how to only iterate the first line.
Reply


Messages In This Thread
Removing leading\trailing spaces - by azizrasul - Oct-20-2022, 02:41 AM
RE: Removing leading\trailing spaces - by rob101 - Oct-20-2022, 04:01 AM
RE: Removing leading\trailing spaces - by azizrasul - Oct-20-2022, 06:01 PM
RE: Removing leading\trailing spaces - by azizrasul - Oct-22-2022, 12:18 AM
RE: Removing leading\trailing spaces - by wavic - Oct-22-2022, 05:27 AM
RE: Removing leading\trailing spaces - by azizrasul - Oct-23-2022, 11:06 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Removing leading whitespaces palladium 1 814 Mar-24-2023, 04:15 PM
Last Post: bowlofred
  How to retrieve records in a DataFrame (Python/Pandas) that contains leading or trail mmunozjr 3 1,943 Sep-05-2022, 11:56 AM
Last Post: Pedroski55
  -i option changes sys.path (removes leading empty string '') markanth 6 2,173 Aug-26-2022, 09:27 PM
Last Post: markanth
  removing spaces msaiahnl 2 1,185 Jul-25-2022, 03:34 PM
Last Post: deanhystad
  How to keep leading zeros with pandas? eeps24 1 6,773 May-20-2020, 07:51 PM
Last Post: deanhystad
  Cancelling 'open directory' leading to crash Fairbz_ 1 2,265 May-08-2020, 03:14 PM
Last Post: DPaul
  [Python3] Trailing newline in readlines. LWFlouisa 4 5,044 Mar-10-2020, 09:57 AM
Last Post: perfringo
  removing spaces/tabs after used .strip() zarize 0 1,661 Sep-11-2019, 12:46 PM
Last Post: zarize
  leading zero number formatting RedSkeleton007 3 4,049 Jan-27-2019, 04:56 PM
Last Post: RedSkeleton007
  Probs with leading zeros falling away :-) Badosc 2 2,965 Dec-04-2018, 08:57 PM
Last Post: Badosc

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020