Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read complex numbers from a file using python

I want to read from a file a set of complex numbers into an array,using Python. I know how to do it only for integers. I tried this,but when I run it ,it says: complex() arg is a malformed string. How can I do to read complex numbers? I just started to learn Python.

f=open("file.txt","r+")
array=[]
for line in f:
     line=line.split()
     if line: 
            line=[complex(i) for i in line]

My file contains only complex numbers:

1+i
1-i
1
2
-3
like image 890
israell Avatar asked Oct 16 '25 03:10

israell


1 Answers

You need to use an engineer's j instead of a mathematician's i for the imaginary unit in python.

You can change something simple like:

line = line.replace('i', 'j').split()

instead of the line=line.split() you have currently, this should fix your code.

Note, there is no need to .split() at all if you have truly one number per line, and you still need to append the results into your container array. I'll leave that bit to you.

As an aside, consider using numpy.loadtxt to parse your file instead, if you have numpy available.

like image 122
wim Avatar answered Oct 17 '25 16:10

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!