Deleting rows in a txt-document using Python

13295
2
06-17-2013 05:03 AM
MaximilianSesselmann
New Contributor
Hi,

first of all, sorry for my poor english...

HERE'S MY PROBLEM:
I have a txt-file in which XY coordinates are stored.
I want to load these coordinates using the WARP-tool. So far, this is no problem but in the first row of the txt- document is some text. Unfortunatly the WARP-tool can only read the coordinates, when there is NO text in front of them.

WHAT I WANT:
of course I could delete the text manually, but I want to have it done automatically. I think this should be possible because the text is always in the first row(s) of the text-document.
The optimal solution for me would be an Python-Script that says: " 1) load all txt-files in the folder C:\... 2) for each file, delete the first 1 or 2 rows 3) save/overwrite the modified files "
In  the end I want to include the script into the Model Builder...

Thanks in advance!
Max
Tags (2)
0 Kudos
2 Replies
JakeSkinner
Esri Esteemed Contributor
Hi Max,

Here is an example how you can remove the beginning lines that contain strings of each text file using the OS and GLOB modules:

import os, glob

strings = ("abcdefghijklmnopqrstuvwxyz")
for file in glob.glob(r"C:\temp\python\*.txt"):
    lines = open(file).readlines()
    with open(file) as myFile:
        for num, line in enumerate(myFile, 1):
            if any(s in line for s in strings):
                val = num
    try:
        open(r'C:\temp\python\newfile.txt', 'w').writelines(lines[val:])
        os.remove(file)
        os.rename(r'C:\temp\python\newfile.txt', file)
    except IndexError:
        pass
0 Kudos
BerndGrubert
New Contributor
Hi, Max.

Maybe this would solve your problem:

Open the textfile in Excel and then build a macro for the correction in the file. Then you can use the macro for every file you have to correct.
0 Kudos