Python Forum

Full Version: .Txt file to .CSV file conversion
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Team,
I am working on below python script which task is "It will take whatever data present in a .txt file and load it into in a .csv file as output.My code is working but the issue is everything is coming as rows in CSV output.

Below is my code:-
# - *- coding: utf- 8 - *-

import os.path
import csv

save_path = "C:\Users\desktop\Python-testing\"

completeName_in  = os.path.join(save_path,'Input_file'+'.txt')
completeName_out = os.path.join(save_path,'Output_file_csv'+'.csv')

 
file1=open(completeName_in)
In_text = csv.reader(file1,delimiter = ';')

file2 =open(completeName_out,'w')
out_csv = csv.writer(file2)

file3 = out_csv.writerows(In_text)

file1.close()
file2.close()
---------------------------------------------------------------------------
I have data in input .txt file:-

Output:
Line no: 1 Line: This is Line1 Line no: 2 Line: This is Line2 Line no: 3 Line: This is Line3
----And I am getting below as output in .csv format:-

Output:
Line no: 1 Line: This is Line1 Line no: 2 Line: This is Line2 Line no: 3 Line: This is Line3
-----------whereas I need help in getting data like this:-
Output:
Line no: Line: 1 This is Line1 2 This is Line1 3 This is Line1
P.S:- I am unable to attach either csv output file or any screenshot.Please bear with me.
need your valuable suggestions.

Thak you
Chinmay Nayak
This was fixed my issue

Tried using front slash / in string literal in save_path.

According to OP input, there are some blank rows, so took care of that with len(row)>0 condition.
(Apr-21-2019, 12:36 PM)Chinmay Wrote: [ -> ]This was fixed my issue

Tried using front slash / in string literal in save_path.

According to OP input, there are some blank rows, so took care of that with len(row)>0 condition.

I think you can just rename text files in mac OS and turn txt files to csv. Or use Microsoft Excel to do that also.

But...

Where I work we would use this method:
import os
import pandas as pd

save_path = "C:\Users\desktop\Python-testing\"

in_filename = os.path.join(save_path,'Input.txt')
out_filename = os.path.join(save_path,'Output.csv')

df = pd.read_csv(in_filename, sep=";")
df.to_csv(out_filename, index=False)