0

This gives FilesNotFoundError. But "newfile.txt" is defined AlreAdy with quotes Around it.

file = open("newfile.txt", "r") print(file.read()) file.close()

15th Feb 2021, 5:18 PM
We Doru
We Doru - avatar
4 odpowiedzi
+ 3
Because you're in read mode. If it didn't find any file that has the name to read. The exception would be raised. If you try this in SoloLearn playground, this never works because the file is never created. But if you try this on a real computer. It will try to find newfile.txt in the current dictionary and if it is found, it will work.
15th Feb 2021, 5:24 PM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
Wedo Ru you should seriously consider going through many articles about file handling in python. 1. About print(file.write("")), here it writes the text to file and return the count of chracters written to file and so print is able to print that value. 2. print(file.read()) file.read() returns the content of file and print() prints it . ""Both methods above have different implementation"" 3.when file is opened in write mode , it creates a new file if it doesn't exists whereas in read mode it tries to read the content from an existing file otherwise it gives an error if it doesn't exists.
15th Feb 2021, 6:08 PM
Abhay
Abhay - avatar
0
CarrieForle But it printed while using write w before the read mode. Example: file=open("newfile.txt", "w") file.write("This has been written to a file") print(file.write("PYTHON8"))#returns and print Only the Number of Characters.why. file.close() file = open("newfile.txt", "r")#When these lines of CODE Are not used the Above write mode only print No. Of ChArActeR And not the string"This has been---" and "PYTHON88".why print(file.read()) file.close()
15th Feb 2021, 5:46 PM
We Doru
We Doru - avatar
0
Also, If we define the newfile, it should work, As the Rules of Coding goes by newfile="ONE" And then file=open(newfile.txt."w"). Now it is Already defined And As expected it should work. But when Call, it sAys Attribute Error.
15th Feb 2021, 5:55 PM
We Doru
We Doru - avatar