Python Forum
CSV to Text File and write a line in newline
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
CSV to Text File and write a line in newline
#1
Hello,
The script generates output as 1 line for each record but I wanted to separate the output that looks like this. Your response is greatly appreciated. Thank you!

Output:
index movie genre year country 1 movie1 action 2020 USA 2 movie2 drama 2019 UK etc...
import csv
from datetime import date
import glob
from multiprocessing import Condition
from re import A
from tkinter import filedialog
import pandas as pd

header = ['index','movie','genre','year','country']

filename = 'dataFile.csv'

inFileData = open(filename, 'r')

rLines = inFileData.readlines() #process file later

inFileData.close()

#printing values in text file
with open('outputFile.txt', 'w') as outFileText:
    outFileText.write('Total Records: ')

    outFileText.write(rLines[0]) #writes header file

    recordIndex = 1
    for line in rLines[1:]:

        if recordIndex < 10:
            outFileText.write(line.replace(",", " ")) #REPLACE commas with whitespace
        
        recordIndex = recordIndex + 1    
           
outFileText.close()

Attached Files

.csv   datafile.csv (Size: 161 bytes / Downloads: 197)
Reply
#2
(Feb-11-2022, 12:35 AM)atomxkai Wrote: The script generates output as 1 line for each record but I wanted to separate the output that looks like this
Why do want structure it like this,its confusing and less readable way to structure itπŸ˜•
Can write some stuff that would do it,the structure make not so easy will be so both ways(parse),
and then look at pandas way to structure it as you have it in import.
first = []
last = []
with open('datafile.csv') as f:
    next(f)
    for line in f:
        line = line.strip()
        first.append('\n'.join(line.split(",", 2)[:2]))
        last.append(' '.join(line.split(",", 2)[-1].split(',')))

lst = list(zip(first, last))
for item in lst:
    print(f'{item[0]}\n{item[1]}\n')
Output:
1 Movie1 ACTION 2021 USA 2 Movie2 DRAMA 2020 UK 3 Movie3 DRAMA 2019 SPAIN 4 Movie4 ACTION 2018 USA 5 Movie5 ACTION 2017 JAPAN
A look at Pandas,that use the standard(Excel,OpenOffice,Googgle sheet) way to structure it.
import pandas as pd

df = pd.read_csv('datafile.csv')
Output:
>>> df REC MOVIE GENRE YEAR COUNTRY 0 1 Movie1 ACTION 2021 USA 1 2 Movie2 DRAMA 2020 UK 2 3 Movie3 DRAMA 2019 SPAIN 3 4 Movie4 ACTION 2018 USA 4 5 Movie5 ACTION 2017 JAPAN
Can turn it around,usually want to transpose to the first one.
Output:
>>> df.transpose() 0 1 2 3 4 REC 1 2 3 4 5 MOVIE Movie1 Movie2 Movie3 Movie4 Movie5 GENRE ACTION DRAMA DRAMA ACTION ACTION YEAR 2021 2020 2019 2018 2017 COUNTRY USA UK SPAIN USA JAPAN
atomxkai likes this post
Reply
#3
Snippsat's method is better, but if you must use csv format:
from pathlib import Path
import csv
import os


def formatfile():
    os.chdir(os.path.abspath(os.path.dirname(__file__)))
    homepath = Path('.')
    infilename = homepath / 'datafile.csv'
    outfilename = homepath / 'outputFile.txt'
    header = 'index\nmovie\ngenre year country\n'

    with infilename.open() as fin, outfilename.open('w') as fout:
        crdr = csv.DictReader(fin)
        fout.write(header)
        for row in crdr:
            fout.write(f"\n{row['REC']}\n{row['MOVIE']}\n" \
                f"{row['GENRE']} {row['YEAR']} {row['COUNTRY']}\n")


if __name__ == '__main__':
    formatfile()
outputFile.txt:
Output:
index movie genre year country 1 Movie1 ACTION 2021 USA 2 Movie2 DRAMA 2020 UK 3 Movie3 DRAMA 2019 SPAIN 4 Movie4 ACTION 2018 USA 5 Movie5 ACTION 2017 JAPAN
BashBedlam and atomxkai like this post
Reply
#4
thanks again snippsat!

it seems bit advance for me but I was able to run it successfully and i'm trying to fully grasp the script. this is a great option for me once i'm fully understand the process. Smile
Reply
#5
Thumbs Up 
thank you Larz60+!

this is awesome! and also a great option for me that i can identify the headers are row[variables].
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Last record in file doesn't write to newline gonksoup 3 404 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  write to csv file problem jacksfrustration 11 1,500 Nov-09-2023, 01:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,427 Nov-09-2023, 10:56 AM
Last Post: mg24
  Facing issue in python regex newline match Shr 6 1,273 Oct-25-2023, 09:42 AM
Last Post: Shr
  How do I read and write a binary file in Python? blackears 6 6,495 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,088 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  File "<string>", line 19, in <module> error is related to what? Frankduc 9 12,540 Mar-09-2023, 07:22 AM
Last Post: LocklearSusan
  Read text file, modify it then write back Pavel_47 5 1,584 Feb-18-2023, 02:49 PM
Last Post: deanhystad
  Getting last line of each line occurrence in a file tester_V 1 857 Jan-31-2023, 09:29 PM
Last Post: deanhystad
  how to read txt file, and write into excel with multiply sheet jacklee26 14 9,893 Jan-21-2023, 06:57 AM
Last Post: jacklee26

Forum Jump:

User Panel Messages

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