Change Floating Point Integer to Integer in Output - python

I am trying to write a Python script to parse Excel data and produce a custom output.
The part where I am stuck is that the output adds ".0" onto the end of any fields from the spreadsheet that contained a number. The string concatenation that I'm doing is treating these numeric values as floating point integers.
How can I make sure that the output is a regular integer rather than a floating point integer for any numeric values?
This is my script so far:
import xlrd
book = xlrd.open_workbook('/Users/doctorwho/test.xls')
sheet = book.sheet_by_index(0)
myList = []
for i in range(sheet.nrows):
myList.append(sheet.row_values(i))
outFile = open('/Users/doctorwho/update.txt', 'wb')
for i in myList:
outFile.write("Test data 1" + str(i[1]) + "Test data 2" + str(i[2])

Try using
for i in myList:
outFile.write("Test data 1" + str(int(i[1])) + "Test data 2" + str(int(i[2]))

Related

Different data is being added to a file than is being printed in the console

I have been writing a program to get all the coordinates within a ten mile radius of any given point and when the distance data is printed its output is different from the data in the file. Not only this but it creates a blank line at the end of the file. What should I do?
import geopy.distance
distance_data = open("Distance from start.txt", "w")
distance_data.truncate()
distance_data_to_add = []
for i in range (360):
bearing = i
lat = 51.8983
long = 177.1822667
for i in range (10):
distance = i
new_lat_long =
geopy.distance.distance(miles=distance).destination((lat, long), bearing=bearing)
distance_data_to_add.append(new_lat_long)
for element in distance_data_to_add:
distance_data.write(str(element) + "\n")
print(distance_data_to_add)
An example line from the file is:
51 56m 30.0669s N, 177 10m 51.749s E
An example of the printed info in the console is:
Point(51.94168524994642, 177.1810413957121, 0.0)
The reason the objects look different in a list is because that is the repr version of them, not the str version. So write repr(element) to the file instead of str(element).
The reason there is a newline at the end of the file is because you write \n after every element.
Replace this:
for element in distance_data_to_add:
distance_data.write(str(element) + "\n")
with this:
distance_data.write('\n'.join(map(repr, distance_to_add)))
That will write the repr of each object, with a newline between each one (but not at the end).
And don't forget distance_data.close() after you finish writing your file.

Python formatting: How to insert blank spaces in between array data elements of data type float

I have a question regarding formatting. I am trying to extract relevant data and insert this data into a fortran file. Thankfully, I am using python to accomplish this task. It just so happens that the fortran file is sensitive to the number of spaces between text. So, this brings me to my question. My array array data looks like:
[[ -1.80251269 12.14048223 15.47522331]
[ -2.63865822 13.1656285 15.97462801]
[ -1.76966256 11.35311123 16.13958474]
[ -0.76320052 12.45171386 15.34209158]
[ -2.12634889 11.84315415 14.48020468]]
[[-14.80251269 1.14048223 1.47522331]
[ -2.63865822 13.1656285 15.97462801]
[ -1.76966256 11.35311123 16.13958474]
[ -0.76320052 12.45171386 15.34209158]
[ -2.12634889 11.84315415 14.48020468]]
[[ -0.80251269 0.14048223 0.47522331]
[ -2.63865822 13.1656285 15.97462801]
[ -1.76966256 11.35311123 16.13958474]
[ -0.76320052 12.45171386 15.34209158]
[ -2.12634889 11.84315415 14.48020468]]
These elements are floats, not strings. For example, I wanted the the first row (and every row thereafter) of the data to look like:
-1.80251269 12.14048223 15.47522331
How would I accomplish this? To be specific, there are 5 white spaces that seperate the left margin from the 1st number, -1.80251269, and 5 white spaces that seperate each of the three numbers. Notice also that I need the array brackets gone, but I suspect I can do this with a trim function. Sorry for my lack of knowledge guys; I do not even know how to begin this problem as my knowledge in Python syntax is limited. Any help or tips would be appreciated. Thanks!
EDIT: this is the code I am using to generate the array:
fo = np.genfromtxt("multlines.inp")
data=scipy.delete(fo, 0, 1)
txt = np.hsplit(data,3)
all_data = np.vsplit(data, 4)
i=0
num_molecules = int(raw_input("Enter the number of molecules: "))
print "List of unaltered coordinates:"
while i < (num_molecules):
print all_data[i]
If you are using NumPy, you can use np.savetxt:
np.savetxt('a.txt', a.reshape(15,3), '%16.8f')
To get
-1.80251269 12.14048223 15.47522331
-2.63865822 13.16562850 15.97462801
-1.76966256 11.35311123 16.13958474
...
(You need to reshape your array into 2-dimensions to do what I think you want).
If you have your data formatted as a list, then I suspect that #kamik423's answer will help you. If it if formatted as a string, you may wish to try something like the following.
def properly_format(line):
nums = line.strip(' []\t').split()
spaces = ' '
return spaces + nums[0] + spaces + nums[1] + spaces + nums[2]
lines = my_array_string.splitlines() #if your data is a multiline string
for line in lines:
formatted_line = properly_format(line)
# do something with formatted_line
Edit: forgot to split the string.
If you don't care about the length of each block you can just do
for i in whateverYouArrayIsCalled:
print str(i[0]) + " " + str(i[1]) + " " + str(i[2])
if you however want to have all the elements to be inline try
for i in whateverYouArrayIsCalled:
print (str(i[0]) + " ")[:20] + (str(i[1]) + " ")[:20] + str(i[2])
where the 20 is the length of each block
(for 2.7)
I will assume that the data array is saved in a data.txt file and you want to save the result into fortran.txt, then:
fortran_file = open('fortran.txt','w') # Open fortran.txt for writing
with open('data.txt',r) as data_file: #Open data.txt for reading
while True:
line = data_file.readline()
if not line: break # EOF
result = line.strip('[]').split()
result = " " + " ".join(result)
fortran_file.write(result)
fortran_file.close()
try this:
import numpy
numpy.set_printoptions(sign=' ')

Want to convert text file of complex numbers to a list of numbers in Python

I have a text file of complex numbers called output.txt in the form:
[-3.74483279909056 + 2.54872970226369*I]
[-3.64042002652517 + 0.733996349939531*I]
[-3.50037473491252 + 2.83784532111642*I]
[-3.80592861109028 + 3.50296053533826*I]
[-4.90750592116062 + 1.24920836601026*I]
[-3.82560512449716 + 1.34414866823615*I]
etc...
I want to create a list from these (read in as a string in Python) of complex numbers.
Here is my code:
data = [line.strip() for line in open("output.txt", 'r')]
for i in data:
m = map(complex,i)
However, I'm getting the error:
ValueError: complex() arg is a malformed string
Any help is appreciated.
From the help information, for the complex builtin function:
>>> help(complex)
class complex(object)
| complex(real[, imag]) -> complex number
|
| Create a complex number from a real part and an optional imaginary part.
| This is equivalent to (real + imag*1j) where imag defaults to 0.
So you need to format the string properly, and pass the real and imaginary parts as separate arguments.
Example:
num = "[-3.74483279909056 + 2.54872970226369*I]".translate(None, '[]*I').split(None, 1)
real, im = num
print real, im
>>> -3.74483279909056 + 2.54872970226369
im = im.replace(" ", "") # remove whitespace
c = complex(float(real), float(im))
print c
>>> (-3.74483279909+2.54872970226j)
Try this:
numbers = []
with open("output.txt", 'r') as data:
for line in data.splitlines():
parts = line.split('+')
real, imag = tuple( parts[0].strip(' ['), parts[1].strip(' *I]') )
numbers.append(complex(float(real), float(imag)))
The problem with your original approach is that your input file contains lines of text that complex() does not know how to process. We first need to break each line down to a pair of numbers - real and imag. To do that, we need to do a little string manipulation (split and strip). Finally, we convert the real and imag strings to floats as we pass them into the complex() function.
Here is a concise way to create the list of complex values (based on dal102 answer):
data = [complex(*map(float,line.translate(None, ' []*I').split('+'))) for line in open("output.txt")]

I want to write math expression in file

ı want to write that command but it is not working
for k in range 900 :
l=len(str(a[k]) **a[ ] is a string which gives random float numbers**
f.write("\n*l") **ı need to write space as the number of string length**
The multiplication needs to be on the string, not in it.
f.write("\n" * l)
I assume that you get length correctly, problem is to write to file.
All you need to do is save to string first and write that string into file.
temp = ''
for k in range 900 :
l=len(str(a[k]) **a[ ] is a string which gives random float numbers**
temp = temp + str(l) + "\n" # store all your values to temp string
f.write(temp) # then write than temp string into file

Python: Calculating the averages of values in a text file

When I run my code below I get a: ValueError: invalid literal for int() with base 10: '0.977759164126' but i dont know why
file_open = open("A1_B1_1000.txt", "r")
file_write = open ("average.txt", "w")
line = file_open.readlines()
list_of_lines = []
length = len(list_of_lines[0])
total = 0
for i in line:
values = i.split('\t')
list_of_lines.append(values)
count = 0
for j in list_of_lines:
count +=1
for k in range(0,count):
print k
list_of_lines[k].remove('\n')
for o in range(0,count):
for p in range(0,length):
print list_of_lines[p][o]
number = int(list_of_lines[p][o])
total + number
average = total/count
print average
My text file looks like:
0.977759164126 0.977759164126 0.977759164126 0.977759164126 0.977759164126
0.981717034466 0.981717034466 0.981717034466 0.981717034466 0.98171703446
The data series is in rows and the values are tab delimited in the text file. All the rows in the file are the same length.
The aim of the script is to calculate the average of each column and write the output to a text file.
int() is used for integers (numbers like 7, 12, 7965, 0, -21233). you probably need float()
Python is limited on handling floating points. These all work fine here but for longer ones as well as arithmetic you are going to want to use the Decimal module.
import Decimal
result = Decimal.Decimal(1)/Decimal.Decimal(5)
print result
Link to the documentation
http://docs.python.org/2/library/decimal.html
Try typing in 1.1 into IDLE and see what your result is.

Categories