user2777262
user2777262

Reputation: 11

Python write to a file r

I am trying to write some basic lines to a text file using Python 3.3.2 (complete beginner here).Not sure why a number returns after the write command line. The number seems to be the length of the string. The string does get stored into the new text file and everything else seems to be okay.

Also :

>>> f=open('testfile.txt','w')
>>> f.write('this is line 1\n')
15

So, the number '15'.. not sure what it means. Every line I write would return an integer.

Upvotes: 0

Views: 461

Answers (2)

SethMMorton
SethMMorton

Reputation: 48725

A better way to write this would be

print('this is line 1', file=f)

Because it is more flexible (it takes any input type, not just str) and it automatically adds the newline character. As an added bonus, it won't echo anything in the python shell.

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

From docs:

f.write(string) writes the contents of string to the file, returning the number of characters written.

Upvotes: 2

Related Questions