saving data from text file to CSV file in python having delimiter as space - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: saving data from text file to CSV file in python having delimiter as space (/thread-29580.html) |
saving data from text file to CSV file in python having delimiter as space - K11 - Sep-11-2020 I have a huge report file. I extracted the required data from it into a new file named "new.txt" I want to save this data in a csv file so that i get the columns and rows properly for each of the headers defined in the file. I am posting my code and the text file contents here...I am not able to get it in the proper form as we get it in excel. Kindly help..I am using python 2.7 and want to do this without using pandas package. SIMPLE_FILE REPORT: Here is my code.import csv outFile = "new.txt" new_file = open(outFile, "a+") new_file.truncate(0) csv_file = "report.csv" def open_file(filename): try: contents = [] with open(filename, 'r') as f1: contents=[line.strip() for line in f1] counter = contents.index("Final report:") for item in contents[counter:]: new_file.write(item+"\n") in_txt = csv.reader(new_file, delimiter = '\t') out_csv = csv.writer(open(csv_file, 'w')) out_csv.writerows(in_txt) except Exception,e: print str(e) exit(1) RE: saving data from text file to CSV file in python having delimiter as space - bowlofred - Sep-11-2020 Please use the python tags for your code. Python2 is very old and no longer maintained. You should be using python3 for any new projects. What part isn't the proper form? Can you give an example of the input? I see a definition for open_file() , but I don't see anywhere that it's called.Why are you opening new_file in append mode and then immediately truncating it? Why not just open it in write mode? |