Python Forum
Removing leading\trailing spaces
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Removing leading\trailing spaces
#5
I wouldn't use CSV at all.

I have a csv like file named data.txt
Output:
id , name , Age 1 , Peter Parker, 1 2 , Charles Xavier , 2 3 , George of the Jungle , 3
It has leading and trailing spaces because someone tried to make it pretty and to lined up the columns.
delim = ","

with open("data.txt", "r") as src:
    with open("data.csv", "w") as dst:
        for line in src:
            values = map(str.strip, line.split(delim))  # Get columns with left and right whitespace removed
            dst.write(",".join(values)+"\n")
# Put it back together, append linefeed and write
This is the result after running the program.
Output:
id,name,Age 1,Peter Parker,1 2,Charles Xavier,2 3,George of the Jungle,3
If you want to overwrite source file.
delim = ","

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

with open("data.csv", "w") as file:
    for line in lines:
        file.write(",".join(line)+"\n")
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 deanhystad - Oct-20-2022, 06:32 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 1,522 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 3,844 Sep-05-2022, 11:56 AM
Last Post: Pedroski55
  -i option changes sys.path (removes leading empty string '') markanth 6 3,729 Aug-26-2022, 09:27 PM
Last Post: markanth
  removing spaces msaiahnl 2 1,893 Jul-25-2022, 03:34 PM
Last Post: deanhystad
  How to keep leading zeros with pandas? eeps24 1 8,929 May-20-2020, 07:51 PM
Last Post: deanhystad
  Cancelling 'open directory' leading to crash Fairbz_ 1 2,841 May-08-2020, 03:14 PM
Last Post: DPaul
  [Python3] Trailing newline in readlines. LWFlouisa 4 6,894 Mar-10-2020, 09:57 AM
Last Post: perfringo
  removing spaces/tabs after used .strip() zarize 0 2,102 Sep-11-2019, 12:46 PM
Last Post: zarize
  leading zero number formatting RedSkeleton007 3 5,095 Jan-27-2019, 04:56 PM
Last Post: RedSkeleton007
  Probs with leading zeros falling away :-) Badosc 2 3,652 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