0

My .txt have a lot of numbers divided in two rows but they are in the brazilian way to write them (this means the number 3.41 is writen as 3,41)... I know how to read each column, I just need to change every comma in the .txt to a dot, but I have no idea how to do that...

There's 3 ways I thought how to solve the problem:

Changing every comma into a dot and overwrite the previous .txt,

Write another .txt with another name, but with every comma changed into a dot,

Import every string (that should be float) from the txt and use replace to change the "," into a ".".

If you can help me with one of the first two ways would be better, especially the first one

(I just imported numpy and don't know how to use others library yet, so if you could help me with the codes and recipes I would really appreciate that) (sorry about the bad english, love ya)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

1

while your question is tagged python, here's a super-simple non-pythonic way, using the sed cmdline utility.

This will replace all commas (,) with dots (.) in your textfile, overwriting the original file:

sed -e 's/,/./g' -i yourtext.txt

Or, if you want the output in a different file:

sed -e 's/,/./g' yourtext.txt > newfile.txt
umläute
  • 28,885
  • 9
  • 68
  • 122
1

Try this:

with open('input.txt') as input_f, open('output.txt', 'w') as output_f:
    for line in input_f.readlines():
        output_f.write(line.replace(',', '.'))

for input.txt:

1,2,3,4,5

10,20,30,40

the output will be:

1.2.3.4.5

10.20.30.40.

Community
  • 1
  • 1
Aaron_ab
  • 3,450
  • 3
  • 28
  • 42
0

umlaute's answer is good, but if you insist on doing this in Python you can use fileinput, which supports inplace replacement:

import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        line.replace(',', '~').replace('.', ',').replace('~', '.')

This example assumes you have .'s and ,'s in your example already so uses the tilde as an interim character while fixing both characters. If you have ~'s in your data, feel free to swap that out for another uncommon character.

If you're working with a csv, be careful not to replace your column delimiter character. In this case, you'll probably want to use regex replace instead to ensure that each comma replaced is surrounded by digits: r'\d,\d'

rgk
  • 985
  • 8
  • 16