gwydion93
gwydion93

Reputation: 1923

"\r\n" also not writing to next line

I am just following a simple Python script to write to a text file. The suggetsed method; adding "\n" to the end didn't work. It is printing within a loopAs I am using Windows, I also tried "\r\n." Still it only prints the last item. I have tried moving everything inside and outside the loop (starting with path and ending with file.close() but no go. What's going on here?

   #Assign variables to the shapefiles
park = "Parks_sd.shp"
school = "Schools_sd.shp"
sewer = "Sewer_Main_sd.shp"

#Create a list of shapefile variables
shapeList = [park, school, sewer]

path = r"C:/EsriTraining/PythEveryone/CreatingScripts/SanDiegoUpd.txt"
open(path, 'w')

for shp in shapeList:
    shp = shp.replace("sd", "SD")
    print shp


    file = open(path, 'w')
    file.write(shp + "\r\n")
    file.close()

Upvotes: 0

Views: 55

Answers (2)

Ray
Ray

Reputation: 184

You can 1) open file outside of the for loop and 2) use writelines

with open(path, 'w+') as f:
    f.writelines([shp.replace("sd", "SD")+'\n' for shp in shaplist])

or

with open(path, 'w+') as f:
    f.writelines(map(lambda s: s.replace("sd", "SD")+'\n', shaplist))

In this way, you open the file once and once the lines are written, the file is automatically closed (because of the [with]).

Upvotes: 1

Rakesh
Rakesh

Reputation: 82755

Open the file outside the loop

Ex:

with open(path, "w") as infile:
    for shp in shapeList:
        shp = shp.replace("sd", "SD")
        infile.write(shp + "\n")

Upvotes: 3

Related Questions