“\r\n”也不写入下一行
"\r\n" also not writing to next line
我只是按照一个简单的 Python 脚本写入文本文件。建议的方法;在末尾添加“\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()
在循环外打开文件
例如:
with open(path, "w") as infile:
for shp in shapeList:
shp = shp.replace("sd", "SD")
infile.write(shp + "\n")
您可以 1) 在 for 循环之外打开文件和 2) 使用 writelines
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])。
我只是按照一个简单的 Python 脚本写入文本文件。建议的方法;在末尾添加“\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()
在循环外打开文件
例如:
with open(path, "w") as infile:
for shp in shapeList:
shp = shp.replace("sd", "SD")
infile.write(shp + "\n")
您可以 1) 在 for 循环之外打开文件和 2) 使用 writelines
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])。