arcpy

2129
12
Jump to solution
03-12-2021 02:25 AM
Mick
by
New Contributor

Can you explain why I have problems with 'with open(out, "w") as k:'? I would like to create a script to use for ArcGIS to add to each file in the folder with text extension 'Hellow'. 

I guess everything because of fileName[:-4] + ".txt",so Python can not define and write in each file.  However, I don't know how to correct it.

import arcpy

inPut = r'C:\12'


arcpy.env.workspace = inPut

myList = arcpy.ListFiles()

for fileName in myList:

if fileName.endswith(".txt"):
     out = fileName[:-4] + ".txt"
     with open(out, "w") as k:
         k.write('Hellow')

0 Kudos
12 Replies
Mick
by
New Contributor

I see. Thank you. Your method deletes everything inside the files and replaces it for only 'Hellow'.

0 Kudos
DavidPike
MVP Frequent Contributor

Yes, your method would have done the same, it's the 'w' write argument which replaces a file if it exists.

python - Difference between modes a, a+, w, w+, and r+ in built-in open function? - Stack Overflow

you may wish to use the 'a' append argument or others.

inPut = r'D:\Downloads\aatester'


arcpy.env.workspace = inPut

myList = arcpy.ListFiles()

for fileName in myList:

    if fileName.endswith(".txt"):
       out = inPut + "\\" + fileName[:-4] + ".txt"
       print(out)
       with open(out, "a") as k:
         k.write('Hellow')
BlakeTerhune
MVP Regular Contributor

Sorry if I convolute this situation more for you @Mick , but I just want to add that you can use a wildcard argument with ListFiles() to only return txt files.

import arcpy
import os

inPut = r'D:\Downloads\aatester'

arcpy.env.workspace = inPut

myList = arcpy.ListFiles("*.txt")

for fileName in myList:
    out = os.path.join(inPut, f"{fileName[:-4]}.txt")

    print(out)
    with open(out, "a") as k:
        k.write('Hellow')

Additionally, I updated your path construction to use os.path.join() so it reliably does the separator. You will also notice the f string formatting for the file name. This will function the same but I just wanted to demonstrate there are multiple ways to accomplish something.