0

I having a .txt file and need to read it in one function and want to use it in another function in python. I am reading file with keyword but we can use open also like file = open("a.txt", "r", encoding="utf-8")

I Tried:

def read_fun():
   with open("a.txt", "r", encoding="utf-8") as file:
       for line in file:
           "doing something"
   **return file**

def operation_on_read():
    **file = read_fun()**
    for i in file:
        "NOT ABLE TO ITERATE HERE ON RETURNED FILE"

So, the above code is not working for me, looking for help.

Thanks, in advance!

jhonD
  • 29
  • 5
  • There are two completely separate problems here, but neither of them has **anything to do with** trying to `return` the file object from a function. The first problem is that file objects **remember a position in the file**, so if you use a loop to read them then you are at the "end" of the file and cannot iterate over them again without seeking back to the beginning. The second problem is that leaving a `with` block closes the file - that is the **explicit purpose** of that syntax. – Karl Knechtel Feb 23 '23 at 12:45
  • Opening a file isn't that expensive an operation, compared to reading through the entire file. Just open it again in `operation_on_read`. – chepner Feb 23 '23 at 13:09
  • Hi chepner, I doing the same thing but its not good practice to read one file again and again so still looking for an solution – jhonD Feb 23 '23 at 13:17

0 Answers0