Python Forum
Help me modify this .txt into .csv with Python - 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: Help me modify this .txt into .csv with Python (/thread-38952.html)



Help me modify this .txt into .csv with Python - mgzz - Dec-13-2022

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? :(


RE: Help me modify this .txt into .csv with Python - Axel_Erfurt - Dec-14-2022

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)