Here are three ways to write a line to file in Python:
- Using open() function with write() (Correct way)
- Using the writelines() (For writing multiple lines to a file)
- Using the print()
Method 1: Using open() function with write()
The correct and easy way to write a line to a file is to use the built-in open() function with the write() method.
This is the directory before creating and writing a new file.txt file:
# The path to the file you want to write to
file_path = 'dir/file.txt'
# The line you want to write
line_to_write = "This is a line of text.\n"
# Open the file in write mode ('w') or append mode ('a')
with open(file_path, 'w') as file:
file.write(line_to_write)
# 'with' ensures that the file is properly closed after its suite finishes
If you open this file, you have content like this as an output:
This method writes the contents of the string data to the file specified by file_path.
We opened the file in ‘w’ mode, which overwrites existing content. To append to the file instead, open it in ‘a’ mode.
Method 2: Using the writelines()
To write multiple lines to a file, use the “writelines()” function.
# The path to the file you want to write to
file_path = 'dir/multi_file.txt'
lines = ["First line\n", "Second line\n", "Third line\n"]
# Open the file in write mode ('w') or append mode ('a')
with open(file_path, 'w') as file:
file.writelines(lines)
# 'with' ensures that the file is properly closed after its suite finishes
Output
Method 3: Using the print()
You can use the print() function to write to files, which can be specifically convenient for formatted output.
# The path to the file you want to write to
file_path = 'dir/print_file.txt'
data1 = "Ayodhya"
data2 = "Ram mandir"
# Open the file in write mode ('w') or append mode ('a')
with open(file_path, 'w') as file:
print(data1, data2, file=file)
print("Another line", file=file)
# 'with' ensures that the file is properly closed after its suite finishes
Output
The ‘file’ argument in print() specifies the output file.
Each print() function call adds a new line automatically unless specified otherwise.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.