How to append "_projected.shp" at the end of each dataset name - python

I have a code that projects a number of shapefiles in a folder to another coordinate system and the projected shapefiles are placed in another folder. For the projected shapefiles, I want to append "_projected" at the end each shapefile name.
What I have so far works for the projection and setting the output files into a specific folder, but the new output files are not showing the "_projected" at the end.
Here is my code
import arcpy
import os
arcpy.env.workspace = "inputdatafolder"
arcpy.env.overwriteOutput = True
outWorkspace = "outputdatafolder"
for infc in arcpy.ListFeatureClasses():
dsc = arcpy.Describe(infc)
if dsc.spatialReference.Name == "Unknown":
print ("skipped this fc due to undefined coordinate system: "+ infc)
else:
outfc = os.path.join(outWorkspace, infc)
outCS = arcpy.SpatialReference('NAD 1983 UTM Zone 10N')
arcpy.Project_management(infc, outfc, outCS)
infc = infc.replace(".shp","_projected.shp")
Since the code works, I am not getting any errors. The file name just isn't replaced with the ending I want it to.

Your code is replacing the text of the filepath of infc, but not actually renaming the file.
Furthermore, outfc is the path to the new projected shapefile you are creating, while infc is the path to the original file. Don't you want outfc to have the "_projected.shp"suffix?
The code below changes the text of the output file path to include "_projected.shp" before calling arcpy.Project_management to create the new file.
import arcpy
import os
arcpy.env.workspace = "inputdatafolder"
arcpy.env.overwriteOutput = True
outWorkspace = "outputdatafolder"
for infc in arcpy.ListFeatureClasses():
dsc = arcpy.Describe(infc)
if dsc.spatialReference.Name == "Unknown":
print ("skipped this fc due to undefined coordinate system: "+ infc)
else:
outfc = os.path.join(outWorkspace, infc).replace(".shp","_projected.shp")
outCS = arcpy.SpatialReference('NAD 1983 UTM Zone 10N')
arcpy.Project_management(infc, outfc, outCS)
I'm also not sure if you're using Describe correctly. You may need to use infc.name when constructing the file paths.

Related

How to save a qgis graph to a shapefile to use in networkx?

I created a graph from a layer using the code below. I want to save this graph to a shapefile for further use in networkx.
I don't want to also save it as a QGIS layer. So how can I simply save it without giving a layer as the first argument of writeAsVectorFormat?
And if I try give an existing layer as argument it gives a strange bug: the code runs, and Windows shows the .shp file at the recent files in Windows Explorer, but when I want to open it it says that the file does not exist, and I also can't see it in the folder where it should be.
I also can't find how to just create a random layer, so if it's really needed to create a layer, can someone tell me how to do it?
Thank you for help
from qgis.analysis import *
vectorLayer = qgis.utils.iface.mapCanvas().currentLayer()
director = QgsVectorLayerDirector(vectorLayer, 12, '2.0', '3.0', '1.0', QgsVectorLayerDirector.DirectionBoth)
# The index of the field that contains information about the edge speed
attributeId = 1
# Default speed value
defaultValue = 50
# Conversion from speed to metric units ('1' means no conversion)
toMetricFactor = 1
strategy = QgsNetworkSpeedStrategy(attributeId, defaultValue, toMetricFactor)
director.addStrategy(strategy)
builder = QgsGraphBuilder(vectorLayer.crs())
startPoint = QgsPointXY(16.8346339,46.8931070)
endPoint = QgsPointXY(16.8376039,46.8971058)
tiedPoints = director.makeGraph(builder, [startPoint, endPoint])
graph = builder.graph()
vl = QgsVectorLayer("Point", "temp", "memory")
QgsVectorFileWriter.writeAsVectorFormat(v1, "zzsh.shp", "CP1250", vectorLayer.crs(), "ESRI Shapefile")
#QgsProject.instance().mapLayersByName('ZZMap07 copy')[0]

How to create a path and extract data from it using python?

I am performing a simulation in Abaqus that consists of the impact of two plates. Imagine that the simulation has 100 frames, what I want is to extract data along a path for a specific frame. I wrote this Python script to extract the velocity and mises data from all the nodes for all frames (the txt file is gigantic), but I want to do it for just a set at a given frame. Does anyone know how to create a node set or path, and then extract the data along this set or path for a certain frame?
Script to export data from abaqus:
import time
import numpy as np
from numpy import savetxt
import math
from odbAccess import *
from textRepr import *
import os, sys
#import matplotlib.pyplot
start_time = time.time()
path = (os.getcwd())
odbName = '%s/Job-1.odb'%path
odb = openOdb(odbName, readOnly=True)
myAssembly = odb.rootAssembly.instances['FIXED-1']
newpath = 'results'
if not os.path.exists(newpath):
os.makedirs(newpath)
steps1 = odb.steps['Step-1'].frames
currentframe1 = []
for c_elem in range(len(steps1)):
currentframe1 = steps1[c_elem]
mises = []
velocity = []
strain = []
displacement = []
fieldvalues_mises = currentframe1.fieldOutputs['S']
fieldvalues_velocity = currentframe1.fieldOutputs['V']
fieldvalues_displacement = currentframe1.fieldOutputs['U']
fieldvalues_strain = currentframe1.fieldOutputs['LE']
vel_set = fieldvalues_velocity.values
disp_set = fieldvalues_displacement.values
mises_set = fieldvalues_mises.values
strain_set = fieldvalues_strain.values
for v in vel_set:
velocity.append(v.data)
for s in strain_set:
strain.append(s.data)
for m in mises_set:
mises.append(m.data)
for d in disp_set:
displacement.append(d.data)
# Vector of frames
vector_frame = c_elem*[1]
with open('velocityFile.txt', 'w') as f:
for i in range(1,len(vector_frame)+1):
f.write('\n\n')
for j in velocity:
f.write(str(j) + 3*' ')
with open('misesFile.txt', 'w') as f:
for i in range(1,len(vector_frame)+1):
f.write('\n\n')
for j in mises:
f.write(str(j) + 3*' ')
Did you open the odb as editable? The default is read only and you CANNOT save something in it, so your line won't be there. This is why abaqus will always tell you that local outputs are only stored in the current session.
Also cathing up on your code snippet, you cannot simply use the name but have to create set in the odb e.g.
odb.rootAssembly.nodeSets['LINE_1']
and use this set in region.
The set has to be present in the assembly.
Yes! Open the odb as editable, create a path of interest and save it in the odb. Use the script to read the variables of interest using the created path. Have a look at Viewing results along a path in the documentation for path creation and obtaining xy results.

Opening files from directory in specific order

I have a folder that contains around 500 images that I am rotating at a random angle from 0 to 360. The files are named 00i.jpeg where i = 0 then i = 1. For example I have an image named 009.jpeg and one named 0052.jpeg and another one 00333.jpeg. My code below works as is does rotate the image, but how the files are being read through is not stepping correctly.
I would think I would need some sort of stepping code chunk that starts at 0 and adds one each time, but I'm not sure where I would put that. os.listdir doesn't allow me to do that because (from my understanding) it just lists the files out. I tried using os.walk but I cannot use cv2.imread. I receive a SystemError: <built-in function imread> returned NULL without setting an error error.
Any suggestions?
import cv2
import imutils
from random import randrange
import os
os.chdir("C:\\Users\\name\\Desktop\\training\\JPEG")
j = 0
for infile in os.listdir("C:\\Users\\name\\Desktop\\training\\JPEG"):
filename = 'testing' + str(j) + '.jpeg'
i = randrange(360)
image = cv2.imread(infile)
rotation_output = imutils.rotate_bound(image, angle=i)
os.chdir("C:\\Users\\name\\Desktop\\rotate_test")
cv2.imwrite("C:\\Users\\name\\Desktop\\rotate_test\\" + filename, rotation_output)
os.chdir("C:\\Users\\name\\Desktop\\training\\JPEG")
j = j + 1
print(infile)
000.jpeg
001.jpeg
0010.jpeg
00100.jpeg
...
Needs to be:
print(infile)
000.jpeg
001.jpeg
002.jpeg
003.jpeg
...
Get a list of files first, then use sort with key where the key is an integer version of the file name without extension.
files = os.listdir("C:\\Users\\name\\Desktop\\training\\JPEG")
files.sort(key=lambda x:int(x.split('.')[0]))
for infile in files:
...
Practical example:
files = ['003.jpeg','000.jpeg','001.jpeg','0010.jpeg','00100.jpeg','002.jpeg']
files.sort(key=lambda x:int(x.split('.')[0]))
print(files)
Output
['000.jpeg', '001.jpeg', '002.jpeg', '003.jpeg', '0010.jpeg', '00100.jpeg']

Perform calculations in every file in the path with loop?

i have a code that finds every file in the directory with a certain extension:
and i want this script to be applied to every shp:
import geopandas as gpd
pst = gpd.read_file(r'C:\Users\user\Desktop\New folder1\PST')#this is not needed in the final because it takes the path by it self
dbound = gpd.read_file(r'C:\Users\user\Desktop\New folder1\DBOUND')#same here
dbound.reset_index(inplace=True)
dbound = dbound.rename(columns={'index': 'fid'})
wdp = gpd.sjoin(pst, dbound, how="inner", op='within')#each dbound and pst from every subfolder
wdp['DEC_ID']=wdp['fid']
this is the list that contains the paths to the shapefiles:
grouped_shapefiles that has these shapefiles:
[['C:\\Users\\user\\Desktop\\eff\\20194\\DBOUND\\DBOUND.shp',
'C:\\Users\\user\\Desktop\\eff\\20194\\PST\\PST.shp'],
['C:\\Users\\user\\Desktop\\eff\\20042\\DBOUND\\DBOUND.shp',
'C:\\Users\\user\\Desktop\\eff\\20042\\PST\\PST.shp'],
['C:\\Users\\user\\Desktop\\eff\\20161\\DBOUND\\DBOUND.shp',
'C:\\Users\\user\\Desktop\\eff\\20161\\PST\\PST.shp'],
['C:\\Users\\user\\Desktop\\eff\\20029\\DBOUND\\DBOUND.shp',
'C:\\Users\\user\\Desktop\\eff\\20029\\PST\\PST.shp'],
['C:\\Users\\user\\Desktop\\eff\\20008\\DBOUND\\DBOUND.shp',
'C:\\Users\\user\\Desktop\\eff\\20008\\PST\\PST.shp']]
and i want something like this:
results = []
for group in grouped_shapefiles:
#here applies the script where i need help to connect in the loop
#and then the export process- the line that follows
#o=a path
out = o +'\result.shp'#here it would be nice to add to the name in the output the name of its folder so it would be unique
data2.to_file(out)
How can i do that?

Error recognizing parameters for a spatial join using ArcPy

I'm trying to iterate a spatial join through a folder - then iterate a second spatial join through the outputs of the first.
This is my initial script:
import arcpy, os, sys, glob
'''This script loops a spatial join through all the feature classes
in the input folder, then performs a second spatial join on the output
files'''
#set local variables
input = "C:\\Users\\Ryck\\Test\\test_Input"
boundary = "C:\\Users\\Ryck\\Test\\area_Input\\boundary_Test.shp"
admin = "C:\\Users\\Ryck\\Test\\area_Input\\admi_Boundary_Test.shp"
outloc = "C:\\Users\\Ryck\\Test\\join_02"
#overwrite any files with the same name
arcpy.env.overwriteOutput = True
#perform spatial joins
for fc in input:
outfile = outloc + fc
join1 = [arcpy.SpatialJoin_analysis(fc,boundary,outfile) for fc in
input]
for fc in join1:
arcpy.SpatialJoin_analysis(fc,admin,outfile)
I keep receiving Error00732: Target Features: Dataset C does not exist or is not supported.
I'm sure this is a simple error, but none of the solutions that have previously been recommended to solve this error allow me to still output my results to their own folder.
Thanks in advance for any suggestions
You appear to be trying to loop through a given directory, performing the spatial join on (shapefiles?) contained therein.
However, this syntax is a problem:
input = "C:\\Users\\Ryck\\Test\\test_Input"
for fc in input:
# do things to fc
In this case, the for loop is iterating over a string. So each time through the loop, it takes one character at a time: first C, then :, then \... and of course the arcpy function fails with this input, because it expects a file path, not a character. Hence the error: Target Features: Dataset C does not exist...
To instead loop through files in your input directory, you need a couple extra steps. Build a list of files, and then iterate through that list.
arcpy.env.workspace = input # sets "workspace" to input directory, for next tool
shp_list = arcpy.ListFiles("*.shp") # list of all shapefiles in workspace
for fc in shp_list:
# do things to fc
(Ref. this answer on GIS.SE.)
After working through some kinks, and thanks to the advice of #erica, I decided to abandon my original concept of a nested for loop, and approach more simply. I'm still working on a GUI that will create system arguments that can be assigned to the variables and then used as parameters for the spatial joins, but for now, this is the solution I've worked out.
import arcpy
input = "C:\\Users\\Ryck\\Test\\test_Input\\"
boundary = "C:\\Users\\Ryck\\Test\\area_Input\\boundary_Test.shp"
outloc = "C:\\Users\\ryck\\Test\\join_01"
admin = "C:\\Users\\Ryck\\Test\\area_Input\\admin_boundary_Test.shp"
outloc1 = "C:\\Users\\Ryck\\Test\\join_02"
arcpy.env.workspace = input
arcpy.env.overwriteOutput = True
shp_list = arcpy.ListFeatureClasses()
print shp_list
for fc in shp_list:
join1 =
arcpy.SpatialJoin_analysis(fc,boundary,"C:\\Users\\ryck\\Test\\join_01\\" +
fc)
arcpy.env.workspace = outloc
fc_list = arcpy.ListFeatureClasses()
print fc_list
for fc in fc_list:
arcpy.SpatialJoin_analysis(fc,admin,"C:\\Users\\ryck\\Test\\join_02\\" +
fc)
Setting multiple environments and using the actual paths feels clunky, but it works for me at this point.

Categories

Resources