calculate area and print it in another txt file in python

Asked

Viewed 100 times

-1

I have an area.txt file:

quadrado;2
retangulo;2;3

I want to create another txt file so it looks like this:

quadrado;2;4
retangulo;2;3;6

I did it this way but it’s wrong:

arq=open('area.txt','r')
conteudo=arq.readlines()
arq.close()

for item in conteudo:
    item=item.replace(',','.')
    a=item.split(';')
    if a[0] == 'quadrado':
        print(float(a[1])*float(a[1]))
    if a[0] == 'retangulo':
        print(float(a[1])*float(a[2]))

arq=open('novo.txt','w')
arq.writelines(conteudo)
arq.close()
  • Cool, missed to say what the problem, put the full error that gives, or the result if it is different than expected. "It’s wrong" is very vague

1 answer

2


Problem

Hello Matheus, from what I understand you want to create a new file by inserting a new column using the parameters of its geometric shape. If it is a 'square', you multiply the second parameter by itself, if it is a 'rectangle', you multiply the second by the third parameter.

What is wrong with your code is that you print the multiplication result on the screen using the function print, while creating a new list content containing the new area column for use within Arq.writelines(content). In addition, there are some little problems in the treatment of the strings. But let’s go to the solution.

Solution 1 - Working with Text Files

In your case, you are manipulating a text file (.txt). This makes it more difficult (and boring) to handle the data.

First we open the file for reading

When we do the reading, Lines receives a list of strings, where each string is a line in the document.

arq = open('area.txt','r')
lines = arq.readlines()
arq.close()

Then we’ll process the data

By iterating through this list, we remove ( n) and break the string by the delimiter (;). Thus, geom is a list of the elements of each line. Depending on each geometric shape, we calculate the area and reinsert into geom using geom.append(str(area)).

With the list containing the new information, we create a new line (new_line) in the same pattern that we read, that is, a string with data separated by semicolons (;) and with n at the end. With the line created, we finally create the list of these strings.

new_lines = []
for line in lines:
    geom = line.strip('\n').split(';')

    # quadrado
    if geom[0] == 'quadrado':
        area = float(geom[1]) * float(geom[1])
        geom.append(str(area))

    # retângulo
    else:    
        area = float(geom[1]) * float(geom[2])
        geom.append(str(area))

    new_line = ';'.join(geom) + '\n'
    new_lines.append(new_line)

We finish saving the file

arq = open('novo.txt','w')
arq.writelines(new_lines)
arq.close()

Output - New.txt file

quadrado;2;4.0
retangulo;2;3;6.0

Solution 2 - Treating CSV file

As we can see, working with strings from the text file has its drawbacks.We have to manually break the rows into columns, remove line breaks, etc. So it follows the same treatment, only using the library csv.

Input file - area.csv

quadrado;2
retangulo;2;3
retangulo;1;2
quadrado;3

Solution

import csv

with open('area.csv', 'r') as f, \
    open('new_area.csv', 'w') as new_f:

    reader = csv.reader(f, delimiter=';')
    writer = csv.writer(new_f, delimiter=';')

    for geom in reader:
        if geom[0] == 'quadrado':
            area = float(geom[1]) * float(geom[1])
            geom.append(str(area))
        else:
            area = float(geom[1]) * float(geom[2])
            geom.append(str(area))

        writer.writerow(geom)

Output file - new_area.csv

quadrado;2;4.0
retangulo;2;3;6.0
retangulo;1;2;2.0
quadrado;3;9.0

Completion

If you are going to work with data, prefer file formats and use libraries that are more optimized for this work. It will save you a lot of time and effort. Big hug.

  • Thank you very much! Just one more doubt if for example this broken number would like it to round how it would do it?

  • Instead of converting the number using float(geom[1]), just convert using int(geom[1]). The int truncates the number and remains only with the integer part.

  • Very explanatory your reply @Leonardoborges, congratulations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.