Python 2.7 _ adding to string deletes string? - python

newby/hobbycoder here.
I wrote a script which runs through a .M3U files and downloads all referenced media. (previews for my record store).
now i manage to get the correct path from the download function this exact way, but for some weird reason the following loop just returns ".mp3"
#write id3 tags
i = 1
for file in os.listdir("/Users/username/Desktop/transmisson"):
artist = str(nucontainer[i][2].replace("/", ""))
track = str(nucontainer[i][1].replace("/",""))
album = str(nucontainer[i][3].replace("/", ""))
filetype = ".mp3"
fullfilename = "/Users/username/Desktop/transmisson/"
+ artist + " - " + track + " - " + album + filetype
EDIT
artist, track, album, filetype all return the correct string
if i concatenate them, they return what i expect
as soon as i add ".mp3" it al goes pear shaped
EDIT
this gives the same problem.
write id3 tags
i = 0
while i < len(nucontainer):
artist = nucontainer[i][2].replace("/", "")
track = nucontainer[i][1].replace("/","")
album = nucontainer[i][3].replace("/", "")
filename = artist + " - " + track + " - " + album + ".mp3"
print filename
i += 1

Separate the paths in os.path.join with commas.
filename = artist + " - " + track + " - " + album + filetype
fullfilename = os.path.join('/Users/username/Desktop/transmisson/', filename)

Your problem might be that you don't 'return' or store anything. Right now, it just loops through the whole directory. Don't you want to store all the fullfilename data or something?
Edit: You don't seem to actualy do something wih file in the loop. Right now you are only referencing i, but i is not defined in your code.
Edit2: Based on your comment that nucontainer is a list of lists, I would assume that you should do something like this:
for i, file in enumerate(os.listdir("/Users/username/Desktop/transmisson")):
artist = str(nucontainer[i][2].replace("/", ""))
track = str(nucontainer[i][1].replace("/",""))
album = str(nucontainer[i][3].replace("/", ""))
filetype = ".mp3"
fullfilename = "/Users/username/Desktop/transmisson/"
+ artist + " - " + track + " - " + album + filetype

Related

When trying to append a string to a list I get an error

I am coding a script in python that automatically writes a file which you can use in the DecentSampler plugin, I am running into an error right now which I am not understanding.
noteGroups = []
firstGroup = True
print(noteGroups)
for file in files: #Writes all the files in the pack.
rfeS = ""
strFile = str(file)
rfe = strFile.split(".", 1)
rfe.pop(-1)
for rfeX in rfe:
rfeS += rfeX
filesSplit = rfeS.split("_", 1)
note = filesSplit[0]
rr = filesSplit[1]
noteList = note.split("delimiter")
print(noteList)
if note not in noteGroups:
noteGroups = noteGroups.append(note)
print(noteGroups)
if firstGroup:
dsp.write("\n </group>")
firstGroup = False
dsp.write("\n <group>")
dsp.write("\n <sample path=\"" + dir + "/" + file + "\" volume=\"5dB\" rootNote=\"" + note + "\" loNote=\"" + note + "\" hiNote=\"" + note + "\" seqPosition=\"" + rr + "\" />")
else:
print(noteGroups)
dsp.write("\n <sample path=\"" + dir + "/" + file + "\" volume=\"5dB\" rootNote=\"" + note + "\" loNote=\"" + note + "\" hiNote=\"" + note + "\" seqPosition=\"" + rr + "\" />")
print(noteGroups)
I am getting the error
File "D:\Python\GUI-test\dshgui.py", line 109, in dspWrite
if note not in noteGroups:
TypeError: argument of type 'NoneType' is not iterable
But if I try this:
noteGroups = ["test", "test"]
note = "A2"
noteGroups.append(note)
print(noteGroups)
It does function properly...
Does anyone know why? And how I can fix it?
The problem is this line:
noteGroups = noteGroups.append(note)
append modifies the list in-place and then it returns None. Don't assign that None value back to the name of the original list. Just do:
noteGroups.append(note)

Test Run Failed: local variable '' referenced before assignment

Long time reader, first time poster!
I've been working on setting up the first piece of automation at my workplace and teaching myself my first programming language at the same time. The end goal is to set up a Sikuli script to run testing overnight.
I keep running into errors that feel like a lack of understanding on basic python principles and I don't have anyone around to teach me.
The function do_math parses a .csv file, does some math, and returns those variables in a tuple. I then assign those results into a variable and try to compare them but I keep running into:
Test Run Failed: local variable 'D2LAverage' referenced before assignment
I've tried assigning D2LAverage in a number of different places, making it global, returning a list vs tuples, but it just keeps getting stuck.
<handler.py>
def do_math():
with open ('C:/Program Files/TrueVision Surgical/DSM/Logs/Latency_' + timestr + '.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
D2L = []
L2D = []
next(csv_file)
for row in csv_reader:
next
D2L.append(float(row[1]))
L2D.append(float(row[2]))
line_count += 1
else:
D2LAverage = 0
L2DAverage = 0
D2LAverage = float(sum(D2L) / len(D2L))
L2DAverage = float(sum(L2D) / len(L2D))
D2Lvar = sum(pow(x-D2LAverage,2) for x in D2L) / len(D2L) # Get varience
D2Lstd = math.sqrt(D2Lvar) # Calculate STD
L2Dvar = sum(pow(x-L2DAverage,2) for x in L2D) / len(L2D) # Get varience
L2Dstd = math.sqrt(L2Dvar) # Calculate STD
return D2LAverage, D2Lstd, L2DAverage, L2Dstd
<start_script.py> - Calling the above do_math
do_math()
results = do_math()
# Specify the path
path = 'C:/Users/AeosFactory/Desktop/'
# Specify the file name
file_name = "Latency_Results" + "_" + str(datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')) + ".txt"
# Create a file at specified location and do comparison
with open (os.path.join(path, file_name), 'a+') as Latency_Results:
if results[0] <= 85:
Latency_Results.write("Pass" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, D2L Average:" + " " + str(round(D2LAverage,2)) + '\n')
else:
Latency_Results.write("Fail" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, D2L Average:" + " " + str(round(D2LAverage,2)) + '\n')
if D2Lstd <= 10:
Latency_Results.write("Pass" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, D2L Standard Deviation:" + " " + str(round(D2Lstd,2)) + '\n')
else:
Latency_Results.write("Fail" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, D2L Standard Deviation:" + " " + str(round(D2Lstd,2)) + '\n')
if L2DAverage <= 85:
Latency_Results.write("Pass" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, L2D Average:" + " " + str(round(L2DAverage,2)) + '\n')
else:
Latency_Results.write("Fail" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, L2D Average:" + " " + str(round(L2DAverage,2)) + '\n')
if L2Dstd <= 10:
Latency_Results.write("Pass" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, L2D Standard Deviation:" + " " + str(round(L2Dstd,2)) + '\n' + '\n')
else:
Latency_Results.write("Fail" + " - " + "4 Screens, Image Mode 1, Surgery, Live, HC, L2D Standard Deviation:" + " " + str(round(L2Dstd,2)) + '\n' + '\n')
With the exception of global variables, variables aren't shared between python files. If you look in start_script.py you never define D2LAverage anywhere. When you attempt to use it during your if statements you raise an error because Python "doesn't know what you're talking about". I think what caught you up is thinking that the name of the values returned is exposed in the scope of where the function was called. All that gets returned is the return value itself.
At the end of do_math() you have the line return D2LAverage, D2Lstd, L2DAverage, L2Dstd, because Python only allows 1 return value per function these get packaged into a tuple.
In start_script.py you call do_math() twice,
once without capturing the return value
once where you assign the return value to results
If you only care about the results of the function, you'll probably want to remove the first call to it.
To access the individual values returned by do_math() you can either access the desired value directly by indexing into the tuple with results[0], or use tuple unpacking to assign the 4 return values to individual variables, with something like D2LAverage, D2Lstd, L2DAverage, L2Dstd = results.

Trouble with apostrophe in arcpy search cursor where clause

I've put together a tkinter form and python script for downloading files from an ftp site. The filenames are in the attribute table of a shapefile, as well as an overall Name that the filenames correspond too. In other words I look up a Name such as "CABOT" and download the filename 34092_18.tif. However, if a Name has an apostrophe, such as "O'KEAN", it's giving me trouble. I try to replace the apostrophe, like I've done in previous scripts, but it doesn't download anything....
whereExp = quadField + " = " + "'" + quadName.replace("'", '"') + "'"
quadFields = ["FILENAME"]
c = arcpy.da.SearchCursor(collarlessQuad, quadFields, whereExp)
for row in c:
tifFile = row[0]
tifName = quadName.replace("'", '') + '_' + tifFile
#fullUrl = ftpUrl + tifFile
local_filename = os.path.join(downloadDir, tifName)
lf = open(local_filename, "wb")
ftp.retrbinary('RETR ' + tifFile, lf.write)
lf.close()
Here is an example of a portion of a script that works fine by replacing the apostrophe....
where_clause = quadField + " = " + "'" + quad.replace("'", '"') + "'"
#out_quad = quad.replace("'", "") + ".shp"
arcpy.MakeFeatureLayer_management(quadTable, "quadLayer")
select_out_feature_class = arcpy.SelectLayerByAttribute_management("quadLayer", "NEW_SELECTION", where_clause)

I am using your ftputil within a python script

I am using your ftputil within a python script to get last modification/creation date of files in directory and I am having few problems and wondered if you could help.
host.stat_cache.resize(200000)
recursive = host.walk(directory, topdown=True, onerror=None)
for root,dirs,files in recursive:
for name in files:
#mctime = host.stat(name).mtime
print name
The above outputs a listing of all files in the directory
host.stat_cache.resize(200000)
recursive = host.walk(directory, topdown=True, onerror=None)
for root,dirs,files in recursive:
for name in files:
if host.path.isfile("name"):
mtime1 = host.stat("name")
mtime2 = host.stat("name").mtime
#if crtime < now -30 * 86400:
#print name + " Was Created " + " " + crtime + " " + mtime
print name + " Was Created " + " " + " " + mtime1 + " " + mtime2
Above produces no output
You've put name in quotes. So Python will always be checking for the literal filename "name", which presumably doesn't exist. You mean:
if host.path.isfile(name):
mtime1 = host.stat(name)
mtime2 = host.stat(name).mtime

Copy a file to a new location and increment filename, python

I am trying to:
Loop through a bunch of files
makes some changes
Copy the old file to a sub directory. Here's the kicker I don't want to overwrite the file in the new directory if it already exists. (e.g. if "Filename.mxd" already exists, then copy and rename to "Filename_1.mxd". If "Filename_1.mxd" exists, then copy the file as "Filename_2.mxd" and so on...)
save the file (but do a save, not a save as so that it overwrites the existing file)
it goes something like this:
for filename in glob.glob(os.path.join(folderPath, "*.mxd")):
fullpath = os.path.join(folderPath, filename)
mxd = arcpy.mapping.MapDocument(filename)
if os.path.isfile(fullpath):
basename, filename2 = os.path.split(fullpath)
# Make some changes to my file here
# Copy the in memory file to a new location. If the file name already exists, then rename the file with the next instance of i (e.g. filename + "_" + i)
for i in range(50):
if i > 0:
print "Test1"
if arcpy.Exists(draftloc + "\\" + filename2) or arcpy.Exists(draftloc + "\\" + shortname + "_" + str(i) + extension):
print "Test2"
pass
else:
print "Test3"
arcpy.Copy_management(filename2, draftloc + "\\" + shortname + "_" + str(i) + extension)
mxd.save()
So, 2 things I decided to do, was to just set the range of files well beyond what I expect to ever occur (50). I'm sure there's a better way of doing this, by just incrementing to the next number without setting a range.
The second thing, as you may see, is that the script saves everything in the range. I just want to save it once on the next instance of i that does not occur.
Hope this makes sense,
Mike
Use a while loop instead of a for loop. Use the while loop to find the appropriate i, and then save afterwards.
The code/pseudocode would look like:
result_name = original name
i = 0
while arcpy.Exists(result_name):
i+=1
result_name = draftloc + "\\" + shortname + "_" + str(i) + extension
save as result_name
This should fix both issues.
thanks to Maty suggestion above, I've come up with my answer. For those who are interested, my code is:
result_name = filename2
print result_name
i = 0
# Check if file exists
if arcpy.Exists(draftloc + "\\" + result_name):
# If it does, increment i by 1
i+=1
# While each successive filename (including i) does not exists, then save the next filename
while not arcpy.Exists(draftloc + "\\" + shortname + "_" + str(i) + extension):
mxd.saveACopy(draftloc + "\\" + shortname + "_" + str(i) + extension)
# else if the original file didn't satisfy the if, the save it.
else:
mxd.saveACopy(draftloc + "\\" + result_name)

Categories