Home > Enterprise >  How to change csv delimiter in same csv file using python?
How to change csv delimiter in same csv file using python?

Time:01-03

I'm trying to change the delimiter in a folder that contains a bunch of csv files. But this code doesn't seem to work, do you have any idea how I can get over this issue? Thank you in advance for your help.

Here's the code:

`

 f1 = open(csv_files[i], "r")
  f2 = open(csv_files[i], "w")
  reader = csv.reader(f1, delimiter=',')
  writer = csv.writer(f2, delimiter=';')
  writer.writerows(csv_files[i])
  print("Delimiter successfully changed")
  f1.close()
  f2.close()

`

this:

    df = pd.read_csv('student-mat.csv', sep=';', encoding='utf-8')

does not work either.

CodePudding user response:

my suggestion is write the DataFrame to a new CSV file with the desired delimiter.

import pandas as pd

df = pd.read_csv(csv_files[i], encoding='utf-8')

df.to_csv(f"{csv_files[i]}_modified.csv", sep=';', encoding='utf-8', index=False)

print("Delimiter successfully changed")
  • Related