How To Write Tsv File in Python

In this tutorial, we will learn how to write data to a TSV (Tab-Separated Values) file using Python. TSV files are similar to CSV (Comma-Seperated Values) files, but use a tab character as a delimiter instead of a comma.

TSV files are a common way to store and share structured data, and they can be easily read and written using Python’s built-in modules and functions. By the end of this tutorial, you’ll be able to create, write, and save TSV files effortlessly!

Step 1: Import the necessary modules

We will use Python’s built-in csv module to write TSV files. The csv module is loaded by using the import statement:

Step 2: Prepare the data

In this step, we’ll create a sample dataset to write to the TSV file. This dataset will be a list of dictionaries, where each dictionary represents an individual row of data in our TSV file. The dictionary keys represent the column names, and the values represent the data in each row.

Step 3: Open the file and create a TSV writer

To write the TSV file, we’ll use Python’s built-in open() function to create a new file. In this example, we’ll create a new file called people.tsv. We will also create a csv.writer object, which will enable us to write rows of data to the TSV file. We will specify the delimiter as a tab character using the delimiter parameter:

Step 4: Write the headers

Before writing the data rows, we’ll write the header row containing the column names. We’ll do this by getting the keys from one of the dictionaries in our dataset and using the writerow() method of the csv.writer object:

Step 5: Write the data rows

To write the data rows, we’ll use a for loop to iterate through our dataset. For each dictionary, we’ll write the values as a row in the TSV file using the writerow() method:

Step 6: Close the file

After writing the header and data rows to the TSV file, we need to close the file. The with statement we’ve been using automatically closes the file once the block of code inside it has been executed, so there’s no need to manually close the file.

Complete Code

Output

Name    Age City
Alice   30  New York
Bob     25  San Francisco
Charlie 22  Los Angeles

Conclusion

In this tutorial, we’ve learned how to create, write, and save TSV files using Python. By following these simple steps, you can easily and efficiently work with TSV files in your Python applications. If you need to read the content of TSV files, you can use the csv.reader class similarly as we did with csv.writer. Happy coding!