How to Write Line to File in Python

Here are three ways to write a line to file in Python:

  1. Using  open() function with write() (Correct way)
  2. Using the writelines() (For writing multiple lines to a file)
  3. 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:

Screenshot before writing a line to file in Python

# 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

Screenshot of creating a new file which has written line

If you open this file, you have content like this as an output:

Output of with open() and write() functions to write a line to a file

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

Output of writelines() function

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

Output of print() function

The ‘file’ argument in print() specifies the output file.

Each print() function call adds a new line automatically unless specified otherwise.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.