2

I tried to convert text file content into a .csv format by reading each and every line using python csv module and converting that to a list. But i couldn't get the expected output and it stores the first line in a row but second line will be stored in 3rd row and 5th so on. Since I am new to python i don't know how to skip the line and store it in the right order.

def FileConversion():
   try:     
        with open('TextToCSV.txt', 'r') as textFile:
            LineStripped = (eachLine.strip() for eachLine in textFile)
            lines = (eachLine.split(" ") for eachLine in LineStripped if eachLine)            
            with open('finalReport.csv', 'w') as CSVFile:
                writer = csv.writer(CSVFile)
                writer.writerow(('firstName', 'secondName', 'designation', "age"))
                writer.writerows(lines)
3
  • Hi @Praveenkumar, I tried your code but it seems to work just fine. Can you show an example of your input and output, just to be sure? Commented Oct 26, 2018 at 12:37
  • And also what you expect to get as a result instead of what you got. Commented Oct 26, 2018 at 12:38
  • Maybe put your write loop on the outside, instead of the inside? Commented Oct 26, 2018 at 12:39

1 Answer 1

3

Why don't you try doing something more simple:

import pandas as pd
aux = pd.read_csv("TextToCSV.txt", sep=" ")
aux.columns=['firstName', 'secondName', 'designation', "age"]

aux.to_csv("result.csv")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.