Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
The write()
and writelines()
functions are file object methods in Python that allow you to write data to a file. In this tutorial, we will learn how to use the write()
and writelines()
functions in Python.
To write data to a file, you need to first open it in write mode ('w') or append mode ('a'). The open()
function is used to open a file and returns a file object.
file = open("example.txt", "w") # Open the file in write mode
Keep in mind that opening a file in write mode will overwrite its content. If the file does not exist, it will be created.
write()
:The write()
function writes a string to the file. The function returns the number of characters written.
text = "Hello, write() function!" num_chars = file.write(text) print(f"Number of characters written: {num_chars}") # Output: 22
writelines()
:The writelines()
function writes a list of strings to the file. Unlike the write()
function, it does not add any newline characters between the strings, so you need to include them if you want to write each string on a new line.
lines = ["Line 1\n", "Line 2\n", "Line 3\n"] file.writelines(lines)
If you want to add data to an existing file without overwriting its content, you can open the file in append mode ('a').
file = open("example.txt", "a") # Open the file in append mode
After you have finished writing data to a file, you should close it using the close()
function. This will ensure that the data is properly flushed to the file and free up any resources used by the file object.
file.close()
with
statement to automatically close the file:You can use the with
statement to automatically close the file when the block of code is exited. This is a recommended practice, as it ensures that the file is always properly closed, even if an exception occurs.
with open("example.txt", "w") as file: file.write("Hello, write() function!\n") file.writelines(["Line 1\n", "Line 2\n", "Line 3\n"])
In summary, the write()
and writelines()
functions in Python allow you to write data to a file. The write()
function is used to write a single string to the file, while the writelines()
function is used to write a list of strings to the file. To write data to a file, you need to first open it in write mode ('w') or append mode ('a') using the open()
function and then close it using the close()
function or a with
statement.
How to use write()
for writing text to a file in Python:
write()
method is used to write a string to a file in Python. It creates or truncates the file if it already exists.with open("example.txt", 'w') as file: file.write("Hello, World!\n")
Writing multiple lines with writelines()
in Python:
writelines()
method is used to write a list of strings to a file, each string representing a line. It does not add newline characters between the lines.lines = ["Line 1", "Line 2", "Line 3"] with open("example.txt", 'w') as file: file.writelines(lines)
Appending data to a file using write()
in Python:
write()
method.with open("example.txt", 'a') as file: file.write("This data is appended.\n")
Character encoding considerations in Python file writing:
with open("example.txt", 'w', encoding='utf-8') as file: file.write("Some non-ASCII characters: é, ü, ñ\n")
Writing to a file in binary mode with write()
in Python:
write()
method with bytes.with open("binary_data.bin", 'wb') as file: file.write(b'\x48\x65\x6C\x6C\x6F') # Writes 'Hello' in binary
Handling newline characters with write()
and writelines()
in Python:
write()
, you may need to explicitly add them. writelines()
doesn't add newline characters between lines.with open("example.txt", 'w') as file: file.write("Line 1\nLine 2\nLine 3\n") # Or use writelines without newline characters
Efficient file writing strategies with write()
and writelines()
:
chunk_size = 1024 # Adjust as needed data = "A" * (10 * 1024 * 1024) # 10 MB of data with open("large_file.txt", 'w') as file: for i in range(0, len(data), chunk_size): file.write(data[i:i + chunk_size])
Using write()
and writelines()
for CSV file creation in Python:
write()
or writelines()
to create a CSV file by formatting the data properly.csv_data = [ "Name, Age, Occupation", "John Doe, 30, Developer", "Jane Smith, 25, Designer" ] with open("example.csv", 'w') as file: file.writelines(line + '\n' for line in csv_data)