Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace within a text file using Python

I have a text file which is about 400,000 lines long. I need to import this text file into a program which only accepts text files which are delimited with spaces or tabs, but this text file is delimited with semi-colons. There is no option in the program I am exporting the text file from (Arcmap) to change the delimination and doing find and replace in the text file itself will literally take 2 days.

I have searched for a script to do this but they all seem to replace the whole LINE of the word file with a space, instead of individually replacing each semi-colon, Leaving me with an empty text file.

Here is a sample of my text file:

"OID_";"POINTID";"GRID_CODE";"POINT_X";"POINT_Y"
;1;-56.000000;200900.250122;514999.750122
;2;-56.000000;200900.750122;514999.750122
;3;-56.000000;200901.250122;514999.750122
;4;-57.000000;200901.750122;514999.750122
;5;-57.000000;200902.250122;514999.750122
;6;-57.000000;200902.750122;514999.750122
;7;-57.000000;200903.250122;514999.750122
;8;-57.000000;200903.750122;514999.750122
;9;-57.000000;200904.250122;514999.750122
;10;-57.000000;200904.750122;514999.750122

I need it to look something like this:

1 -56.000000 200900.250122 514999.750122
2 -56.000000 200900.750122 514999.750122
like image 705
Alice Duff Avatar asked Jan 20 '11 10:01

Alice Duff


People also ask

Can you find and replace in a text file?

Open the text file in Notepad. Click Edit on the menu bar, then select Replace in the Edit menu. Once in the Search and Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options section for further information and help.


1 Answers

How about this:

sed -i 's/;/ /g' yourBigFile.txt

This is not a Python solution. You have to start this in a shell. But if you use Notepad, I guess you are on Windows. So here a Python solution:

f1 = open('yourBigFile.txt', 'r')
f2 = open('yourBigFile.txt.tmp', 'w')
for line in f1:
    f2.write(line.replace(';', ' '))
f1.close()
f2.close()
like image 199
eumiro Avatar answered Oct 12 '22 00:10

eumiro