0

Problem with python

I created file with text and want to add another text, but it shows me number, why? my=open('my.txt', 'w') my.write('pervaya stroka') my=open('my.txt') with open('my.txt') as my_new_file: contents=my_new_file.read() print(contents) with open('my.txt', 'a') as f: new=f.write('vtoraya stroka') print(new) So it shows me the first text, but when i add the other one, it shows me 14 Where is the problem?

29th Aug 2020, 4:44 PM
muhammed hilal
muhammed hilal - avatar
6 Respuestas
+ 7
Some issues in the code, that can result in problems. Find some comments in the code. if you open a file and don't close it correctly, all the content of the file can get lost. my=open('my.txt', 'w') my.write('pervaya stroka') my.close() # file has to be closed after using it, except you use "with open ..." #my=open('my.txt') # not used with open('my.txt') as my_new_file: contents=my_new_file.read() print(contents) with open('my.txt', 'a') as f: new=f.write('vtoraya stroka') print(new) # prints the number of characters written to the file
29th Aug 2020, 5:00 PM
Lothar
Lothar - avatar
+ 4
You are printing the return from the write function, which return the length of the string you wrote, Instead you should open it after appending the value in read mode then print it
29th Aug 2020, 4:57 PM
Ruba Kh
Ruba Kh - avatar
+ 3
my=open('my.txt', 'w') my.write('pervaya stroka ') my.close() with open('my.txt', 'a') as f: f.write('vtoraya stroka') with open('my.txt') as my_new_file: new=my_new_file.read() print(new)
29th Aug 2020, 5:17 PM
Ruba Kh
Ruba Kh - avatar
+ 2
Because you are reading the file two times one after wrting the first line and the second after appending. Remove the part for reading and printing the first time.
29th Aug 2020, 5:14 PM
Ruba Kh
Ruba Kh - avatar
+ 1
Oh, thank you very much! But now it prints Pervaya stroka Pervaya stroka vtoraya stroka So why it duplicate the first text?
29th Aug 2020, 5:12 PM
muhammed hilal
muhammed hilal - avatar
+ 1
Ooooooo, i see Thank you) It works)
29th Aug 2020, 5:18 PM
muhammed hilal
muhammed hilal - avatar