Home>

There are two variables where the division result is stored, i.e. fractions with long tails. How can I save them to txt. I open tht:

file= open ('res1.txt', 'a +')

I want to further write these two variables then I successively add variables and a space between them

file.write (str (var1))
file.write (str (""))
file.write (str (var2))

but now I want to make sure what is going on

read= open ('res1.txt', 'r')
read

get< _io.TextIOWrapper name= 'res1.txt' mode= 'r' encoding= 'cp1251' >

Obviously something is wrong.

Question: how can I enter the result of two variables and the symbol between them, and then see the result of this saving. Ideally, I would like to keep them rounded, without long tails.


without further ado, I made a variable, where everything I need is bogged down as a single line. or can it be more rational?

An example of working with files docs.python.org/3/tutorial/...

Dmitry Sokolov2021-02-24 02:27:42

thank. in that description it says that a.) the append mode when opening further recording adds something: "and 'a' opens the file for appending; any data written to the file is automatically added to the end". I open it with file= open ('res1.txt', 'a'), then I try to write a variable, then a space, then a variable; at the output I have 18 characters, then 1, then 18. i.e. overwriting, not adding. but how to add? because if the arguments of the writing method are separated by commas, b. error that this method has only 1 argument.

Versteher2021-02-24 02:27:42
  • Answer # 1
    read= open ('res1.txt', 'r')
    read
    

    get< _io.TextIOWrapper name= 'res1.txt' mode= 'r' encoding= 'cp1251' >

    Obviously something is wrong.

    Yes, obviously. You just opened the file, but you didn't read anything from it, you just display the file object on the screen. To read data from a file, call for example the methodread:

    file= open ('res1.txt', 'r')
    print (file.read ())
    

    To output data rounded, use, for example, f-strings:

    file.write (f '{var: .3} {var2: .3}')
    

    .3means rounding to 3 decimal places.

Trends