How to Convert a Dataframe to a Text File in Python?

Estimated read time 2 min read

To convert a DataFrame to a text file in Python, you can use the to_csv() method provided by the Pandas library. The to_csv() method allows you to save a DataFrame to a CSV (Comma-Separated Values) file, which can be read as a text file. Here’s an example:

import pandas as pd

def dataframe_to_text_file(df, file_path, delimiter=','):
    df.to_csv(file_path, sep=delimiter, index=False)

# Example usage
data = {
    'Name': ['John', 'Jane', 'Sam'],
    'Age': [25, 30, 35],
    'City': ['New York', 'London', 'Paris']
}
df = pd.DataFrame(data)

file_path = 'output.txt'  # Path to the output text file
delimiter = '\t'  # Delimiter to use (e.g., tab, comma, etc.)

dataframe_to_text_file(df, file_path, delimiter)

In this example, the dataframe_to_text_file function takes three parameters: df, which is the DataFrame you want to convert, file_path, which is the path to the output text file, and delimiter, which specifies the delimiter to use in the text file (default is comma).

The to_csv() method is called on the DataFrame df with the provided file path and delimiter. The index=False argument ensures that the index column is not included in the output file.

After executing the code, the DataFrame will be saved as a text file at the specified file path, with the data separated by the chosen delimiter.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply