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')
Solved! Go to Solution.
I see. Thank you. Your method deletes everything inside the files and replaces it for only 'Hellow'.
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')
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.