Oct-20-2022, 06:32 PM
(This post was last modified: Oct-20-2022, 06:32 PM by deanhystad.)
I wouldn't use CSV at all.
I have a csv like file named data.txt
This is the result after running the program.
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")