how to convert dataframe to text file in python code example

Example 1: save df to txt

df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep='\t', mode='a')

Example 2: dataframe to txt

df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep=' ', mode='a')

Example 3: convert a text file data to dataframe in python without pandas

import csv

with open('log.txt', 'r') as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (line.split(",") for line in stripped if line)
    with open('log.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title', 'intro'))
        writer.writerows(lines)

Tags:

Misc Example