def read_file(): ''' Reads contents from the text file (questions.txt) @return a list of five random questions ' | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

def read_file(): ''' Reads contents from the text file (questions.txt) @return a list of five random questions '

Read Python file

5th Aug 2022, 7:36 AM
Sebetoane Benediction Letlhogile
Sebetoane Benediction Letlhogile - avatar
1 Answer
+ 1
open() function is used to open a file in python which takes two arguments, the filename and mode. Based on the your question's tag, you want to open the file as "read-only", in that case use the "r" mode as the second argument. 🔸 file = open("questions.txt", "r") Then to read the contents of that file, use read() method and print its returned value. 🔸 print(file.read()) And don't forget to close the file after. 🔸 file.close() NOTE: this won't work on sololearn, and will only work on your local device if you have a questions.txt file inside your current directory. If not in current directory, use the absolute path. (example: folder/questions.txt) TIP: it seems like you interchanged your question's title and description. You can edit it, "Read Python file" should be the title and then either paste your code in the description or save it on a code bit.
5th Aug 2022, 7:58 AM
noteve
noteve - avatar