Saving averages in text file - python

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.

Related

How to concatenate multiple variables?

I have three UV sensors - integers output; one BME280 - float output (temperature and pressure); and one GPS Module - float output.
I need to build a string in this form - #teamname;temperature;pressure;uv_1;uv_2;uv_3;gpscoordinates#
and send them via ser.write at least one time per second- I'm using APC220 Module
Is this the right (and fastest) way to do it?
textstr = str("#" + "teamname" + ";" + str(temperature) + ";" + str(pressure) + ";" + str(uv_1) + ";" + str(uv_2) + ";" + str(uv_3) + "#")
(...)
ser.write(('%s \n'%(textstr)).encode('utf-8'))
You may try something like this:
vars = [teamname, temperature, pressure, uv_1, uv_2, uv_3, gpscoordinates]
joined = ';'.join( map( str, vars ))
ser.write( '#%s# \n', joined )
If using python 3.6+ then you can do this instead
textstr = f"#teamname;{temperature};{pressure};{uv_1};{uv_2};{uv_3}# \n"
(...)
ser.write((textstr).encode('utf-8'))
If teamname and gpscoordinates are also variables then add them the same way
textstr = f"#{teamname};{temperature};{pressure};{uv_1};{uv_2};{uv_3};{gpscoordinates}# \n"
(...)
ser.write((textstr).encode('utf-8'))
For more info about string formatting
https://realpython.com/python-f-strings/
It might improve readability to use python's format:
textstr = "#teamname;{};{};{};{};gpscoordinates#".format(temperature, pressure, uv_1, uv_2, uv_3)
ser.write(('%s \n'%(textstr)).encode('utf-8'))
assuming gpscoordinates is text (it's not in your attempted code). If it's a variable, then replace the text with {} and add it as a param to format.

Concatenate multi-column text files containing numbers & nan

I have a folder named 17307 which contains some .ismr files (essentially just CSV files) named like
SEPT307A.17_.ismr,
SEPT307B.17_.ismr,
SEPT307C.17_.ismr,.... upto SEPT307X.17_.ismr.
I want to concatenate all these into a single text file using Python. I tried:
st = 'path/to/folder'
a = input('Enter first part of file') #i.e. SEPT307 in file name
alph = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X']
yr = input('enter the year')
last = '_.ismr'
for letter in alph:
st1 = st + "a" + alph + "." + "yr" + last
fp = open(st1, "r")
data=np.append(data, np.fromfile(fp, dtype=list))
i.e. I am trying to put everything into data and later copy data to a separate text file.
However I am getting this error:
TypeError: Can't convert 'list' object to str implicitly
Can anyone kindly suggest some way for doing this?
Looks like the error coming from this line:
st1 = st + "a" + alph + "." + "yr" + last
Where alph is the full list of your alphabet. It should be:
st1 = st + "a" + letter + "." + "yr" + last
The issue is that you are trying to concatenate a list with a str.

variable isn't defined but it is

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.

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))

User input to text file

I know how to write the input to a text file (Python 2.7.x).
How would you go about having pre-written text and user input on the same line?
See:
f.write("Artist: ", toart + "\n")
The error I get is:
f.write("Artist: ", toart + "\n")
TypeError: function takes exactly 1 argument (2 given)
Any help?
Change f.write("Artist: ", toart + "\n") ==> f.write("Artist: " + toart + "\n").
Try this :
f.write("Artist: " + toart + "\n")
# ^^^
This way you get only one string to be passed...

Categories