-1

I am trying to write a code which takes all the .csv files in a directory, which are semi colon delimited, and formats the .csv file into columns. This is my code:

import pandas as pd
import glob
path = r'C:...'
csv_file = path + "\*.csv"
allFiles = glob.glob(path + "\*.csv")

for file in allFiles:
 dataframe = pd.read_csv(file, delimiter=';')
 dataframe.to_csv(file, encoding='utf-8', index=False)

I have tested the dataframe = part of this code, it works as desired for one .csv file, but I cannot get this to repeat for all files in the folder. Any ideas? Thanks.

James
  • 113
  • 1
  • 5

2 Answers2

2

If all you want to do is change ; to , in the files, something like this would work:

for root, dirs, files in os.walk("/dirname/"):
    csv_files = [ff for ff in files if ff.endswith('.csv')]
    for f in csv_files:
        with open(f) as tf:
            s = f.read()
        with open(f, "w") as tf:
            f.write(s.replace(";", ","))
turtlemonvh
  • 9,149
  • 6
  • 47
  • 53
1

You can use pandas and do something like this:

import pandas as pd

df1 = pd.read_csv("csv_semicolon.csv", delimiter=";")
df1.to_csv("csv_tab.csv", sep="\t", index=False)