0

Got very strange syntax error in Python3 when I want to write a .txt file. Also happened when I don't use with open() as fz.

with open('ff.txt','w') as fz:
    for m in range(17):
        for n in range(25):
            x = 425-m-n*17
            fz.writelines(str(x + ' '))
        fz.writelines('\n')
fz.close()

3 Answers 3

1

I receive this error TypeError: unsupported operand type(s) for +: 'int' and 'str'

As @Scibor said the writelines must receive a list. But I think that the error you have is into concatenating a string with an array, in this line:

fz.writelines(str(x + ' '))

try like this:

with open('ff.txt','w') as fz:
    for m in range(17):
        for n in range(25):
            x = 425-m-n*17
            fz.writeline(str(x )+ ' ')
        fz.writeline('\n')
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, my answer was incomplete. Thank you for providing OP with the full solution!
@Miro If this worked for you, kindly accept it as the answer. :)
0

With the 'with' statement the 'close' method isn't required (exiting the block the file is automatically closed).

1 Comment

This is a valid critique of the code, but not the true cause of the error.
0

writelines takes a list as a parameter, not a string. Change this line:

fz.writelines(str(x + ' '))

to:

fz.writelines([str(x + ' ')])

and this line:

fz.writelines('\n')

to:

fz.writelines(['\n'])

Alternatively, just use write instead.

1 Comment

Thanks for reply. But it will throw me this error: TypeError: unsupported operand type(s) for +: 'int' and 'str'

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.