arcpy shp转txt
时间: 2023-09-10 22:11:36 浏览: 154
以下是使用arcpy将shapefile转换为txt的步骤:
1. 导入arcpy模块:
```
import arcpy
```
2. 设置工作空间:
```
arcpy.env.workspace = "path/to/folder/containing/shapefile"
```
3. 定义要素类:
```
fc = "name_of_shapefile.shp"
```
4. 定义输出txt文件的路径和名称:
```
output_file = "path/to/output_file.txt"
```
5. 使用arcpy.da.SearchCursor迭代要素类中的所有要素:
```
with arcpy.da.SearchCursor(fc, ["field1", "field2", "field3"]) as cursor:
with open(output_file, "w") as f:
for row in cursor:
f.write(str(row[0]) + "," + str(row[1]) + "," + str(row[2]) + "\n")
```
在此代码中,我们使用SearchCursor迭代要素类,并将要素的每个字段的值写入txt文件中。我们使用“,”作为字段值之间的分隔符,并在每行的末尾添加换行符“\n”。
6. 运行代码并检查输出txt文件。
完整的代码如下:
```
import arcpy
# 设置工作空间
arcpy.env.workspace = "path/to/folder/containing/shapefile"
# 定义要素类
fc = "name_of_shapefile.shp"
# 定义输出txt文件的路径和名称
output_file = "path/to/output_file.txt"
# 使用arcpy.da.SearchCursor迭代要素类中的所有要素
with arcpy.da.SearchCursor(fc, ["field1", "field2", "field3"]) as cursor:
with open(output_file, "w") as f:
for row in cursor:
f.write(str(row[0]) + "," + str(row[1]) + "," + str(row[2]) + "\n")
```
请注意,此代码仅适用于具有三个字段的要素类。如果您的要素类具有不同数量的字段,请相应地更改代码。此外,您可以更改分隔符和行结束符,以使输出文件符合您的要求。
阅读全文