4

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
3
  • 3
    Please post some part of your file as well. Commented May 9, 2013 at 6:22
  • 1
    On my file I have 5 complex numbers: 1+i ,1-i, 1,2 and -3; but there are written one per line,without comma between. Commented May 9, 2013 at 6:24
  • @israell you need to show the file Commented May 9, 2013 at 6:24

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.