0
Read a txt file, print it, make a list, order the list
I'm able to do the exercise, but if I don't open the same file two times, the second part of the exercise (make a list and order it) don't run. Is that normal? https://code.sololearn.com/cN0BnVsbXueK/#py I'm sorry, my english is very bad...
5 Respuestas
+ 5
Max Ba the reason it doesn't work two times is because you can only read from the file once. Once you read it, the next read() call will return None.
Since you didn't modify it, why not use the initial f_contents? Use it twice, without even opening or reading the file again.
Also, can you share the whole exercice? I may help if I know exactly what it says.
+ 4
Max Ba no, you have to manually close the file with f.close()
However, the recommended way to open files is using the "with" statement, which closes the file automatically for you.
This is the syntax:
with open('romeo.txt') as f:
contents = f.read()
# whatever you want here
It also mentioned in the course.
+ 1
Aymane Boukrouh the original excercise do not mention to print the original file romeo.txt as it is, but I'm trying to practice Python and English :-)
Thank you
https://code.sololearn.com/cN0BnVsbXueK/#py
+ 1
Aymane Boukrouh: Since you didn't modify it, why not use the initial f_contents? Use it twice, without even opening or reading the file again.
This works greats. Thank you very much.
C:\Users\max\Desktop\Python Gadget\ex_08_01>ex_08_04.py
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
0
So the file is closed automatically after the first command?