making list of lines from file when you use withthe file object returned by open(is only available inside the with block that contains it if you want to retain access to file' contents outside the with blockyou can store the file' lines in list inside the block and then work with that list you can process parts of the file immediately and postpone some processing for later in the program the following example stores the lines of pi_digits txt in list inside the with block and then prints the lines outside the with blockfilename 'pi_digits txtu with open(filenameas file_objectlines file_object readlines( for line in linesprint(line rstrip()at the readlines(method takes each line from the file and stores it in list this list is then stored in lineswhich we can continue to work with after the with block ends at we use simple for loop to print each line from lines because each item in lines corresponds to each line in the filethe output matches the contents of the file exactly working with file' contents after you've read file into memoryyou can do whatever you want with that dataso let' briefly explore the digits of pi firstwe'll attempt to build single string containing all the digits in the file with no whitespace in itpi_string py filename 'pi_digits txtwith open(filenameas file_objectlines file_object readlines( pi_string ' for line in linespi_string +line rstrip( print(pi_stringprint(len(pi_string)we start by opening the file and storing each line of digits in listjust as we did in the previous example at we create variablepi_stringto