Python Forum
Help me modify this .txt into .csv with Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help me modify this .txt into .csv with Python
#1
Question 
Im having A LOT of difficulty. I have an assignment which is to modify this file https://easyupload.io/axktqq through Python into CSV cp1252 (Excel) with ";" as the column separator. Im not allowed to use import csv. As you can see, this file is a list of movies with their year, duration, rating, description, etc. all these need to be into their own column (column labels in french) and one film per line.

Title and restriction needs to be in the title() format, the year/duration/nbvotes/metascore into int(eger), the revenue/score into float, and the description into title() with no space before/after the text.

Here is what I did so far (basically nothing):

f = open("data_groupe_11-12_B.txt", 'r')

texte = f.read()

f.close()

lines = texte.split('&')

data = []

data.append(lines[0].split(',') + ['Titre'] + ['Année'] + ['Durée (min)'] + ['Revenu (M$)'] + ['Nombre de votes'] + ['Score'] + ['Metascore'] + ['Restriction'] + ['Description'])
Can you please help me? :(
Larz60+ write Dec-13-2022, 06:47 PM:
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.
Fixed for you this time. Please use BBCode tags on future posts.
Reply
#2
lines = texte.split('&')

is wrong, your splitter is &&. & is on begin and end only.

in_text = ""
out_text = ""

# open file, read and split
with open("data_groupe_11-12_B.txt", "r") as f:
    in_text = f.read()[1:-1].split("&&")

# for replacements
repl = ["title", "year", "duration", "score", "nbvotes", "revenue", "revenue", "restriction", "desc"]

# set headers
out_text = ";".join(repl).title()
out_text += "\n"

for line in in_text:
    line = line.replace(",", ";")
    
    for ch in repl:
        if ch in line:
            # replacing, (for example title= year= ...)
            line=line.replace(f"{ch}=", "").replace("  ", "").strip()
    
    out_text += f"{line}\n"
        
    
print(out_text)

# save as semicolon seperated text file
with open("result.csv", "w") as f:
    f.write(out_text)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to modify python script to append data on file using sql server 2019? ahmedbarbary 1 1,232 Aug-03-2022, 06:03 AM
Last Post: Pedroski55
  I am writing a car rental program on python. In this function I am trying to modify aboo 2 2,754 Aug-05-2021, 06:00 PM
Last Post: deanhystad
  modify the color a string of characters in python 3.6 atlass218 10 5,662 Feb-28-2019, 03:20 PM
Last Post: atlass218

Forum Jump:

User Panel Messages

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