My company asks to convert txt files to .csv files. Could you advise how to write a Python script for ArcGIS?
Solved! Go to Solution.
You won't use arcpy as it is nothing more than a python module but you can use the re (regular expression) module to do it:
import re
myFile = r'C:\temp\Coords.txt'
with open(myFile,'r+') as f:
text = f.read()
text = re.sub(' ',',',text)
f.seek(0)
f.write(text)
f.truncate()
f.close()
Assuming you have the file C:\temp\Coords.txt that looks like this:
-111.45 40.57
-112.05 40.06
I stole this right from https://www.kite.com/python/answers/how-to-update-and-replace-text-in-a-file-in-python
The bigger question is the *.txt files in comma separated values format?
Otherwise it would be a simple renaming operation.
And in any event, the filename extension doesn't need to be *.csv for it to be read as one, it is the contents that are important
A previous answer provides the solution, which just needs to be put within a loop
Solved: Using Python to split and rename file - Esri Community
There is no comma.
Then a sample of the input would be needed, otherwise you have to read the file, parse it on spaces or tabs and reassemble
I have only two spaces between coordinates in my files. Can you recommend a code to replace two spaces for a comma in the script?
I use numpy
fname = r"c:\temp\space.txt"
a = np.loadtxt(fname, delimiter=" ")
outname = fname[:-3] + "csv"
np.savetxt(outname, a, fmt='%f', delimiter=", ")
a text file
1.0 2.0 3.0
4.0 5.0 6.0
as csv file
1.000000, 2.000000, 3.000000
4.000000, 5.000000, 6.000000
you can format as you see fit.
Thank you, can you recommend any extra options with arcpy?
NumPy has been a standard package in Esri's Python deployment for years. If your Python deployment has ArcPy, it has NumPy installed too.
You won't use arcpy as it is nothing more than a python module but you can use the re (regular expression) module to do it:
import re
myFile = r'C:\temp\Coords.txt'
with open(myFile,'r+') as f:
text = f.read()
text = re.sub(' ',',',text)
f.seek(0)
f.write(text)
f.truncate()
f.close()
Assuming you have the file C:\temp\Coords.txt that looks like this:
-111.45 40.57
-112.05 40.06
I stole this right from https://www.kite.com/python/answers/how-to-update-and-replace-text-in-a-file-in-python
Can you recommend how to use not only one file to convert but a folder with one hundred files?