Computer Science · Ch 2 — File Handling in Python
The write() method
The write() method
The write() method is how you actually put data into a text file. It does not create a file — that is the job of the open() function with the 'w' mode. Once the file is open for writing, write() sends a string into it.
The method takes exactly one argument: a string. It writes that string to the file and then returns the number of characters it just wrote. This return value is an integer, and it equals the length of the string you passed. For example, if you write "Hey I have started using files in Python\n", the method returns 41 — because that string (including the newline character) is 41 characters long.
The newline character \n is counted as a single character, not two. So "Hello\n" has length 6, not 7.
You must manually add \n at the end of every line you want to end. The write() method does not automatically insert a newline — unlike print(), which does. If you forget the \n, the next write() call will continue writing on the same line, right after the previous text.
Here is the basic sequence:
- Open the file in write mode:
myobject = open("myfile.txt", 'w') - Write a string:
myobject.write("Hey I have started using files in Python\n") - Close the file:
myobject.close()
When you run this, Python displays 41 (the return value) on the screen. That is just the output of the write() call — it does not mean the number 41 is written into the file. The file itself contains only the string.
Writing numbers requires an extra step. Since write() only accepts a string, you must convert any numeric data to a string first using the str() function. For example:
myobject = open("myfile.txt", 'w')
marks = 58
myobject.write(str(marks)) # converts 58 to "58"
myobject.close()
Here, write() returns 2 because the string "58" has two characters. The file will contain the text 58, not the number 58.
If you try to pass a number directly — like myobject.write(marks) — Python will raise a TypeError. You must always use str() for numbers. …