Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python &引用\r\n“;也不写下一行_Python_Python 2.7_Loops_File Writing - Fatal编程技术网

Python &引用\r\n“;也不写下一行

Python &引用\r\n“;也不写下一行,python,python-2.7,loops,file-writing,Python,Python 2.7,Loops,File Writing,我只是按照一个简单的Python脚本编写一个文本文件。建议的方法;在结尾添加“\n”无效。它是在循环中打印的。因为我正在使用Windows,我也尝试了“\r\n”。但它仍然只打印最后一项。我尝试过将所有内容移动到循环内外(从path开始,以file.close()结束),但没有成功。这里发生了什么 #Assign variables to the shapefiles park = "Parks_sd.shp" school = "Schools_sd.shp" sewer = "Sewe

我只是按照一个简单的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()

在循环外部打开文件

Ex:

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

在循环外部打开文件

Ex:

with open(path, "w") as infile:
    for shp in shapeList:
        shp = shp.replace("sd", "SD")
        infile.write(shp + "\n")
您可以1)在for循环之外打开文件,2)使用writeline

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

通过这种方式,您可以一次打开文件,一旦写入行,文件就会自动关闭(因为[with])。

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

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


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

也许您的意思是在循环之前打开文件,然后在循环之后关闭它。否则,您将在循环的每一圈中覆盖您的文件。您的
打开
调用将在循环内部设置
'w'
。这将有效地覆盖每个迭代操作。你们都是对的。我只需要'file=open(路径'w')一次,并且在循环之外。现在它工作了。也许你的意思是在循环之前打开你的文件,然后在循环之后关闭它。否则,您将在循环的每一圈中覆盖您的文件。您的
打开
调用将在循环内部设置
'w'
。这将有效地覆盖每个迭代操作。你们都是对的。我只需要'file=open(路径'w')一次,并且在循环之外。现在它起作用了。