2

I can't close this file, as the file is directly fed into the 'lines'-list.

I have tried closing with command lines.close() but it doesn't work.

def readfile():
    lines = [line.rstrip('\n') for line in open('8ballresponses.txt', 'r')]  
    print(random.choice(lines))

I don't get an error, but i want to be able to close the file.

  • 4
    ``with open() as somename:`` automatically closes the file – PySaad Oct 24 '19 at 11:50
  • 1
    You should use `with open('8ballresponses.txt', 'r') as your_file:` and it will be auto-closed at the end of the `with` block. – Klaus D. Oct 24 '19 at 11:50
  • `open('8ballresponses.txt', 'r').close()` Maybe? – Sid Oct 24 '19 at 11:50
  • @Sid That would render the `open()` pretty much useless. – Klaus D. Oct 24 '19 at 11:51
  • @Sid I doubt it. In this case, you would open the file and close it immediately. How would you then read from it? – Tobias Brösamle Oct 24 '19 at 11:51
  • Close it afterwards, I meant. It was a guess. Sorry guys! – Sid Oct 24 '19 at 11:52
  • CPython will automatically close the file once it's out of scope (so in this case, after the list comprehension is done), but this is not guaranteed for all Python implementations. – L3viathan Oct 24 '19 at 11:53
  • 2
    @L3viathan this is not even _garanteed_ by the CPython implementation - it's currently the case, has been for decades and will possibly still be the case for some times, but it's an implementation detail no one should rely upon (for production code at least). – bruno desthuilliers Oct 24 '19 at 12:04

5 Answers5

2

Instead of file object, lines is a list , so you can't close it. And you should store file object open('8ballresponses.txt', 'r') with a variable for closing it later:

def readfile(file_path):
    test_file = open(file_path, 'r')
    lines = [line.rstrip('\n') for line in test_file]
    test_file.close()
    print(random.choice(lines))

Or simply use with "to close a file in python, without a file object":

def readfile(file_path):
    with open(file_path, 'r') as test_file:
        lines = [line.rstrip('\n') for line in test_file]
        print(lines)
Gantrol
  • 191
  • 2
  • 8
1

you can use with open command. this will automatically handle all the test cases failure etc. (inbuild try except and finally in python)

below is example similiar to your code

import random

def readfile():
    lines = []
    with open(r"C:\Users\user\Desktop\test\read.txt",'r') as f:
        lines = f.readlines()
    print(random.choice(lines))
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

Use with this will close implicitly after the block is complete

with  open('8ballresponses.txt', 'r') as file:
      lines = [ line.rstrip("\n") for line in file ]  
Yugandhar Chaudhari
  • 3,831
  • 3
  • 24
  • 40
0

In this post "When the with ends, the file will be closed. This is true even if an exception is raised inside of it."

You manually invoke the close() method of a file object explicitly or implicitly by leaving a with open(...): block. This works of course always and on any Python implementation.

Alexall
  • 423
  • 2
  • 12
0

You can use try and finally block to do the work.

For example :

def readfile():
    file = open('8ballresponses.txt', 'r')
    try:
        lines = [line.rstrip('\n') for line in file]  
        print(random.choice(lines))
    finally:
        file.close()
Masudur Rahman
  • 1,585
  • 8
  • 16