“\r\n”也没有写入下一个lin

2024-09-28 20:35:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是按照一个简单的Python脚本来编写一个文本文件。suggetsed方法;在结尾添加“\n”无效。它是在一个循环内打印当我使用Windows时,我也尝试了“\r\n”。它仍然只打印最后一个项目。我尝试过在循环内外移动所有内容(从path开始,以file.close()结束),但没有成功。这是怎么回事?你知道吗

   #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()

Tags: path方法脚本parkcloseopensdvariables
2条回答

您可以1)在for循环外打开文件,2)使用writeline

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

或者

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

这样,您只需打开一次文件,一旦写入行,文件就会自动关闭(因为[with])。你知道吗

在循环外打开文件

例如:

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

相关问题 更多 >