import csv import math inFile = open("Data.txt", "r+") outFile = open("Analysis.txt", "r+") temp_data = () guess = [] myReader = csv.reader(inFile) with open("Data.txt", "r+") as reader: for line in reader: temp_data = line.split(',') guess.append(temp_data[1]) for line in temp_data: for i in line: if i.isdigit() == True: int(round(temp_data)) inFile.close()
Explanation: So far, this is for a school project I am doing in analyzing weather data. Data.txt is just weather data collected from a government website in the correct format and the code above first imports things, open the necessary files, and deals with the data. I need help figuring out how to round all of the float data values into integers with the ’round’ function in python and then finding the mean, median, average, and mode for all the data. Analysis.txt is just taking the middle column out of the data.txt and writing it there.
Advertisement
Answer
It seems there are a lot of redundant code in your included example, so I am a bit unsure on what you are trying to do, but please see a suggestion below. I am basically iterating through all items in your line, converting them to floats and rounding them.
Changed the .isdigit()
to a try/except clause for converting to float
guess = [] with open("Data.txt", "r+") as reader: for line in reader: temp_data = [] for i in line.split(','): try: temp_data.append(round(float(i))) except ValueError: temp_data.append(i) guess.append(temp_data[1])
To write it to a new file you could do the following
with open("Analysis.txt", "w") as writer: for g in guess: writer.write(str(g))
If you wish to separate the written data, you could do so using the following code (separating with n
)
with open("Analysis.txt", "w") as writer: writer.writelines('n'.join(map(str,guess)))