variable isn't defined but it is - python

I have seen this question multiple times but none of them can apply to my code and none of it makes sense to my code. So I am sorry for asking this question.
I have written up a code where the data from previous inputs are written into a csv file. The name of the variable is called file and i have numerous of these for different inputs. But when I try to close the csv it comes up with the error:
NameError: name 'file' is not defined
Here is the code:
if classCode=="1":
file=open("class1.csv","w")
file.write("name, correct\n" + name + "," + str(correct) + "\n")
elif classCode=="2":
file=open("class2.csv","w")
file.write("name, correct\n" + name + "," + str(correct) + "\n")
elif classCode=="3":
file=open("class3.csv","w")
file.write("name, correct\n" + name + "," + str(correct) + "\n")
file.close()
I don't know why it says that 'file' isn't defined when I clearly have for all three. Am i just being stupid?

What happens if the class code is not 1,2 or 3. If all class code do the same thing you can make the filename dynamic, instead of repeating the code several times.
class_file=open("class{}.csv".format(classCode),"w")
class_file.write("name, correct\n" + name + "," + str(correct) + "\n")
class_file.close()

file variable will only declare when classCode is either "1", "2" or "3" otherwise it will not declare and error will come.
you should make sure either control goes to any of the if statement or you should declare this variable outside If statement.

Related

How to format a long string while following pylint rules?

I have a very simple problem that I have been unable to find the solution to, so I thought I'd try my "luck" here.
I have a string that is created using variables and static text altogether. It is as follows:
filename_gps = 'id' + str(trip_id) + '_gps_did' + did + '_start' + str(trip_start) + '_end' + str(trip_end) + '.json'
However my problem is that pylint is complaining about this string reprensentation as it is too long. And here is the problem. How would I format this string representation over multiple lines without it looking weird and still stay within the "rules" of pylint?
At one point I ended up having it looking like this, however that is incredible "ugly" to look at:
filename_gps = 'id' + str(
trip_id) + '_gps_did' + did + '_start' + str(
trip_start) + '_end' + str(
trip_end) + '.json'
I found that it would follow the "rules" of pylint if I formatted it like this:
filename_gps = 'id' + str(
trip_id) + '_gps_did' + did + '_start' + str(
trip_start) + '_end' + str(
trip_end) + '.json'
Which is much "prettier" to look at, but in case I didn't have the "str()" casts, how would I go about creating such a string?
I doubt that there is a difference between pylint for Python 2.x and 3.x, but if there is I am using Python 3.x.
Don't use so many str() calls. Use string formatting:
filename_gps = 'id{}_gps_did{}_start{}_end{}.json'.format(
trip_id, did, trip_start, trip_end)
If you do have a long expression with a lot of parts, you can create a longer logical line by using (...) parentheses:
filename_gps = (
'id' + str(trip_id) + '_gps_did' + did + '_start' +
str(trip_start) + '_end' + str(trip_end) + '.json')
This would work for breaking up a string you are using as a template in a formatting operation, too:
foo_bar = (
'This is a very long string with some {} formatting placeholders '
'that is broken across multiple logical lines. Note that there are '
'no "+" operators used, because Python auto-joins consecutive string '
'literals.'.format(spam))

Saving averages in text file

I am making an average calculator in python, i have to save the averages in a text file and have done it like this:
Mean = statistics.mean(aver)
Mode = statistics.mode(aver)
Medi = statistics.median(aver)
file = open("Averages.txt", "a")
file.write("\n\nYour numbers are" + aver +
"\nMean : " + Mean +
"\nMode : " + Mode +
"\nMedian : " + Medi)
(aver is a list of numbers i am finding the average of)
when i try to run this part of the code, i recieve the error message:
TypeError: Can't convert 'list' object to str implicitly
I tried basic stuff like adding 'str' on but it doesnt help.
file.write("\n\nYour numbers are" + **aver** +
this would be better as something like this:
aver = " " + ", ".join(aver) + " "
which converts your list to a comma separated string.

Trouble inputting interger values into an SQL statement within ArcGIS

So I am defining a function for use in a ArcGIS tool that will verify attributes, catch errors, and obtain user input to rectify those error. I want the tool to select and zoom to the segment that is being currently assessed so that they can make an informed decision. This is what I have been using, and it works well. But the CONVWGID is the variable that will be changing, and I'm not sure how to input that variable into an SQL statement without causing errors.
This is how I had tested the logic:
def selectzoom():
arcpy.SelectLayerByAttribute_management(Convwks, "NEW_SELECTION", " [CONVWGID] = 10000001")
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
df.zoomToSelectedFeatures()
arcpy.RefreshActiveView()
Then I needed to work the variable into the function in order to accept different CONVWGID values, which gives me a Runtime/TypeError that I should have known would happen.
Runtime error -
Traceback (most recent call last): - File "string", line 1, in module - TypeError: cannot concatenate 'str' and 'int' objects
def selectzoom(convwkgid):
delimfield = '" [CONVWGID] = ' + convwkgid + ' "'
arcpy.SelectLayerByAttribute_management(Convwks, "NEW_SELECTION", delimfield)
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
df.zoomToSelectedFeatures()
arcpy.RefreshActiveView()
And when I alter the delimfield line to change the integer into a string, it selects all of the attributes in the entire feature class. Not just the one that had been passed via the function call.
delimfield = '"[CONVWGID] = ' + str(convwkgid) + '"'
I'm not amazing with SQL and maybe I'm missing something basic with this statement, but I can't figure out why it won't work when I'm basically giving it the same information:
"[CONVWGID] = 10000001"
'"[CONVWGID] = ' + str(convwkgid) + '"'
It turned out to be the extra inclusion of Double quotes inside of my single quotes that raised this problem.
Thanks to #Emil Brundage for the help!
Let's say convwkgid = 10000001
'"[CONVWGID] = ' + str(convwkgid) + '"' doesn't equal "[CONVWGID] = 10000001"
'"[CONVWGID] = ' + str(convwkgid) + '"' would actually be '"CONVWGID] = 10000001"'
Try instead:
'[CONVWGID] = ' + str(convwkgid)

Reading data from Excel sheets and building SQL statements, writing to output file in Python

I have an excel book with a couple of sheets. Each sheet has two columns with PersonID and LegacyID. We are basically trying to update some records in the database based on personid. This is relatively easy to do TSQL and I might even be able to get it done pretty quick in powershell but since I have been trying to learn Python, I thought I would try this in Python. I used xlrd module and I was able to print update statements. below is my code:
import xlrd
book = xlrd.open_workbook('D:\Scripts\UpdateID01.xls')
sheet = book.sheet_by_index(0)
myList = []
for i in range(sheet.nrows):
myList.append(sheet.row_values(i))
outFile = open('D:\Scripts\update.txt', 'wb')
for i in myList:
outFile.write("\nUPDATE PERSON SET LegacyID = " + "'" + str(i[1]) + "'" + " WHERE personid = " + "'" + str(i[0])
+ "'")
Two problems - when I read the output file, I see the LegacyID printed as float. How do I get rid of .0 at the end of each id? Second problem, python doesn't print each update statement in a new line in the output text file. How to I format it?
Edit: Please ignore the format issue. It did print in new lines when I opened the output file in Notepad++. The float issue still remains.
Can you turn the LegacyID into ints ?
i[1] = int(i[1])
outFile.write("\nUPDATE PERSON SET LegacyID = " + "'" + str(i[1]) + "'" + " WHERE personid = " + "'" + str(i[0])
+ "'")
try this..
# use 'a' if you want to append in your text file
outFile = open(r'D:\Scripts\update.txt', 'a')
for i in myList:
outFile.write("\nUPDATE PERSON SET LegacyID = '%s' WHERE personid = '%s'" %( int(i[1]), str(i[0])))
Since you are learning Python (which is very laudable!) you should start reading about string formatting in the Python docs. This is the best place to start whenever you have a question light this.
Hint: You may want to convert the float items to integers using int().

Replacing filenames in python with new filenames [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Rename Files in Python
Hey all, I am creating a script in Python to wrap a number of OS commands related to bulk image editing, and most of the tasks are completed, however I am stumped on one task (a seemingly simple one at that).
When I scan pictures on my scanner, I get a filename similar to this:
201105151110_0001A.jpg
where the first part is some sort of a timestamp (which I want to replace), however I wanted to make that an input variable (where I, or other users could just paste that into the command line, if I'm using another scanner where the filename structure could be different. 0001A means the front side of the first photo/document, and I would like to keep that part of the filename.
I have three variables set up:
old_prefix = input(bcolors.PROMPT + "Enter the prefix to replace: " + bcolors.ENDC)
new_prefix = input(bcolors.PROMPT + "Enter the new prefix: " + bcolors.ENDC)
working_directory
working_directory is the variable from another part of the code, which is where the images would be located. The color part is just so I can colorize the output and make it easier to read. There would be anywhere from 1-1000 files in the directory when I work on it.
This script will be run on Linux.
Thank you!
---EDIT---
Sorry for wasting your time guys, it seems I overlooked some information in the question linked here by Kiril Kirov, the code that I came up with, which works is:
elif retouch_option == "06":
print(" ")
old_prefix = input(bcolors.PROMPT + "Enter the prefix to replace: " + bcolors.ENDC)
new_prefix = input(bcolors.PROMPT + "Enter the new prefix.......: " + bcolors.ENDC)
print(bcolors.OUTPUT + " ")
for fname in glob(working_directory + "*.jpg"):
keeper = fname[-9:]
print("Renaming image", keeper)
os.rename(fname, fname.replace(old_prefix, new_prefix))
I think it should be safe, since it is just replacing the old_prefix variable with the new_prefix variable. Is this true? If not I'd definitely appreciate feedback, although this seems to be working fine so far.
something like:
sep = '_'
try:
prefix,keeper = filename.split(sep)
except: # filename does not match desired structure
print "not processed: no '" + sep + "' in '"+ filename + "'"
else: # split succeeded:
if prefix == old_prefix:
filename = new_prefix + sep + keeper
# more processing...
else:
print "prefix doesn't match in '" + filename + "'"

Categories