Python Forum
Converting .txt to .csv file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting .txt to .csv file
#21
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.')
buran write Jan-19-2024, 08:02 PM:
spam link removed

Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#22
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']
>>>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,392 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  [split] Help- converting file with pyton script eltomassito 6 3,237 Jul-02-2021, 05:29 PM
Last Post: snippsat
  Help- converting file with pyton script grinleon 3 2,478 Sep-23-2020, 11:48 AM
Last Post: grinleon

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020