calculate area and print it in another txt file in python

0

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 the following 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()
    
asked by anonymous 18.11.2018 / 21:03

1 answer

3

Problem

Hello Matheus, so I understand you want to create a new file by inserting a new column using the parameters of its geometric form. 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 result of the multiplication on the screen using the print function, while you should create a new content list containing the new column area to use within arq.writelines (content) . In addition, there are some problems in the handling of strings. But let's get to the solution.

Solution 1 - Working with Text Files

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

First we open the file for reading

When we read, lines receives a list of strings, where each string is a line of the document.

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

Then we treat the data

Iterating through this list, we remove the (\ n) and break the string by the delimiter (;). In this way, geom is a list with the elements of each line. Depending on each geometric shape, we calculate the area and reinserted 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 we read, that is, a string with the data separated by a semicolon (;) and with the \ n at the end. With the line created, we finally created 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)

Finished 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 - Handling CSV file

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

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

Conclusion

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

    
19.11.2018 / 05:04