1

I have 10 files, each one of them has 2 columns with 1000000 rows. I'm trying to replace all comma's in my files with dots. I used the following script

import glob
import os, os.path

list =[]
for filename in glob.glob("inputfile/*"):
    with open(filename, 'r') as searchfile:
        for line in searchfile:
            if ',' in line:
                replace=line.replace(",", ".")
                list.append(replace)
                f = open(filename, 'w')
                for item in list:
                    f.write(item)

It's working, but the resulted files have 2 columns and just 365 rows, which means that I lost 999635 rows of my data.

can you help me please??

 Edit:

 sample of my data
-0,0222950  0,1429029
-0,0216510  0,1419368
-0,0226171  0,1406487
-0,0222950  0,1393607
Cashoo
  • 31
  • 1
  • 8

1 Answers1

1

This is one approach. Write to a temp file and after processing rename the temp file to original file and delete old file

Ex:

import glob
import os, os.path

base_path = "inputfile/"
for filename in glob.glob("{}\*".format(base_path)):
    path, file_name = os.path.split(filename)
    with open(filename, 'r') as searchfile, open(os.path.join(path, "temp_{}".format(file_name)), 'w') as searchfile_out:
        for line in searchfile:
            if ',' in line:
                line = line.replace(",", ".")
            searchfile_out.write(line)   #Write to temp file

    os.rename(filename, os.path.join(path, "OLD_{}".format(file_name)))    #Rename old file
    os.rename(os.path.join(path, "temp_{}".format(file_name)), filename)  #Rename temp file to original file
Rakesh
  • 81,458
  • 17
  • 76
  • 113