简体   繁体   中英

Python using open(file) variable more than once?

Is it possible to define a variable as open("file.txt", "a") and call it more than once so you don't have to keep typing open("file.txt", "a") ?

I tried, but it doesn't seem to work for me. I keep getting the error message:

ValueError: I/O operation on closed file.

My code looks like:

x = open("test.txt", "a")
with x as xfile:
    xfile.write("hi")

#works fine until I try again later in the script

with x as yfile:
    yfile.write("hello")

Question: Is there a way to do this that I'm missing?

(My apologies if this question is a repeat, I did search google and SO before I posted a new question.)

If you don't want to close the file right away, don't use a with statement and close it yourself when you're done.

outfile = open('test.txt', 'w')

outfile.write('hi\n')

x = 1
y = 2
z = x + y

outfile.write('hello\n')

outfile.close()

Typically you use the with statement when you want to open a file and do something with that file immediately, and then close it.

with open('test.txt', 'w') as xfile:
    do something with xfile

However, it is best practice to take care of all your I/O with a single file at once if you can. So if you want to write several things to a file, put those things into a list, then write the contents of the list.

output = []

x = 1
y = 2
z = x + y
output.append(z)

a = 3
b = 4
c = a + b
output.append(c)

with open('output.txt', 'w') as outfile:
    for item in output:
        outfile.write(str(item) + '\n')

The with statement closes the file automatically. It is good to do everything related to the file inside the with statement (opening a file multiple times is also not a good idea).

with open("test.txt", "a") as xfile:
    # do everything related to xfile here

But, if it doesn't solve your problem then don't use the with statement and close the file manually when the work related to that file is done.

From docs :

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.

You example doesn't make much sense without more context, but I am going to assume that you have a legitimate need to open the same file multiple times. Answering exactly what you are asking for, you can try this:

x = lambda:open("test.txt", "a")

with x() as xfile:
    xfile.write("hi")

#works fine until I try again later in the script

with x() as yfile:
    yfile.write("hello")

The usual way to use with statements (and indeed I think the only way they work) is with open("text.txt") as file: .

with statements are used for handling resources that need to be opened and closed.

with something as f:
    # do stuff with f

# now you can no longer use f

is equivalent to:

f = something
try:
    # do stuff with f
finally:    # even if an exception occurs
    # close f (call its __exit__ method)
# now you can no longer use f

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM