繁体   English   中英

Python多次使用open(file)变量吗?

[英]Python using open(file) variable more than once?

是否可以将变量定义为open("file.txt", "a")并多次调用它,所以您不必继续键入open("file.txt", "a")

我尝试过,但似乎对我不起作用。 我不断收到错误消息:

ValueError:对关闭的文件进行I / O操作。

我的代码如下:

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")

问题:有什么方法可以实现我所缺少的吗?

(如果这个问题重复出现,我深表歉意,在发布新问题之前,我确实搜索过Google和SO。)

如果您不想立即关闭文件,请不要使用with语句并在完成后自行关闭它。

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

outfile.write('hi\n')

x = 1
y = 2
z = x + y

outfile.write('hello\n')

outfile.close()

通常with当您要打开文件并立即对该文件执行某些操作然后将其关闭时,可以使用with语句。

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

但是,最佳实践是,如果可以的话,一次处理一个文件即可处理所有I / O。 因此,如果您想将多个内容写入文件,请将这些内容放入列表中,然后写入列表中的内容。

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')

with语句自动关闭文件。 最好在with语句中执行与文件相关的所有操作(多次打开文件也不是一个好主意)。

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

但是,如果不能解决问题,则不要使用with语句并在完成与该文件相关的工作时手动关闭该文件。

docs

在处理文件对象时,最好使用with关键字。 这样做的好处是,即使在执行过程中引发了异常,文件在其套件完成后也将正确关闭。

没有更多上下文,您的示例就没有多大意义,但是我将假定您确实有必要多次打开同一文件。 确切回答您的要求,您可以尝试以下操作:

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")

with语句一起使用的常用方法(实际上,我认为它们的唯一工作方式)是with open("text.txt") as file:

with语句用于处理需要打开和关闭的资源。

with something as f:
    # do stuff with f

# now you can no longer use f

等效于:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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