In this tutorial we’ll see different options to write to a file in Python.
- Using write() method you can write the passed string to a file.
- Using writelines(lines) method you can write a list of lines.
- Writing file in binary mode.
1. Using write() method for file writing in Python
f.write(string) writes the contents of string to the file and returns the number of characters written. For writing to a file in Python file should be opened in write mode. Note that opening in write mode (‘w’) will either create the file if it doesn’t exist or overwrite the file if already exists.
def write_file(fname): try: f = open(fname, 'w') f.write("This is Line 1.\n") f.write("This is Line 2.") finally: f.close() write_file("F:/knpcode/Python/test.txt")
Here write_file() method takes the file path as argument and opens that file in write mode. Two lines are written to the file and then the file is closed.
Another way to open the file is using with keyword which automatically closes the file. Using with open is preferred as it makes code shorter.
def write_file(fname): with open (fname, 'w') as f: chars_written = f.write("This is Line 1.\n") print('Characters written to the file', chars_written); f.write("This is Line 2.")
As you can see now try-finally block is not required as with open automatically closes the file once file operations are done.
If you want to write any other type of object then it has to converted to the string (in text mode) or a bytes object (in binary mode) before writing it to the file. For example in the following program we want to write a tuple to the file for that it has to be converted to str first.
def write_file(fname): with open(fname, 'w') as f: value = ('One', 1) s = str(value) # convert the tuple to string f.write(s)
2. Using writelines(lines) method you can write a list of lines.
If you have a list of lines then you can use writelines() method to write it.
def write_file(fname): with open(fname, 'w') as f: lines = ["This is the first line\n", "This is the second line\n", "This is the third line"] f.writelines(lines)
3. Using ‘w+’ mode to write and read file.
Following program opens a file in ‘w+’ mode for both writing and reading. Program also uses tell() method to get the current position of the file pointer and seek() method to move to the beginning of the file.
def write_read_file(fname): with open(fname, 'w+') as f: f.write("This is the first line.\n") f.write("This is the second line.\n") f.flush() print("Current position of file pointer- ", f.tell()) f.seek(0, 0) s = f.read() print('Content- ', s)
4. Writing a binary file in Python
If you want to write a binary file you need to open file in ‘wb’ mode. In the following Python program to copy an image an image file is opened in binary mode and then written to another file.
def copy_file(): try: # Opened in read binary mode f1 = open('F:/knpcode/Java/Java Collections/collection hierarchy.png', 'rb') # Opened in write binary mode f2 = open('F:/knpcode/Python/newimage.png', 'wb') b = f1.read() f2.write(b) print('Coying image completed...') finally: f1.close() f2.close()
- Python I/O – Open, Read, Write Files
- Python Program to Append to a File
- Python Program to Read a File
- Input from User in Python – input() function
- How to Write to a File in Java
- Read File Asynchronously in Java
That’s all for the topic Python Program to Write a File. If something is missing or you have something to share about the topic please write a comment.
You may also like