Python Forum

Full Version: Converting .txt to .csv file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
In Python, you can convert a .txt file to a .csv file using the csv module. Here's a simple example assuming your .txt file is structured with lines of values separated by spaces or tabs:

import csv

# Specify the path for the input .txt file
input_txt_path = 'input.txt'

# Specify the path for the output .csv file
output_csv_path = 'output.csv'

# Read data from the .txt file
with open(input_txt_path, 'r') as txt_file:
    # Assuming the values in each line are separated by spaces or tabs
    lines = [line.strip().split() for line in txt_file]

# Write data to the .csv file
with open(output_csv_path, 'w', newline='') as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerows(lines)

print(f'Conversion from {input_txt_path} to {output_csv_path} completed.')
how about:
>>> import csv
>>> fauxfile = [ 'mary had\ta little\tlamb', 'Its Fleece was\twhite as snow']
>>> for n, item in enumerate(fauxfile):
...     fauxfile[n] = item.replace(' ', ',').replace('\t', ',')
... 
>>> fauxfile
['mary,had,a,little,lamb', 'Its,Fleece,was,white,as,snow']
>>>
Pages: 1 2 3