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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With