如何写入文件然后删除它

问题描述 投票:0回答:3

我是一名 C# 程序员,现在需要学习 Python。到目前为止,这是我的第二天。 我需要写入一个文件,读取它,然后删除它。 在 C# 中这很容易。

string strPath = @"C:\temp\test.txt";
using (StreamWriter writer = new StreamWriter(strPath))
{ writer.WriteLine("XYZ");}

string readText = File.ReadAllText(strPath);

File.Delete(strPath);

通过使用关闭流

在Python中我想到了这个:

with open(strPath, "xt") as f:
    f.write("XYZ")
f.close()

f = open(strPath, "r")
strReadFile = f.read()

os.remove(strPath)

但尽我所能,我仍然收到错误消息,告诉我该文件正在使用中。 因此我用谷歌搜索:“Python写入读取和删除文件”但什么也没出现

谢谢 帕特里克

python file readfile delete-file writefile
3个回答
1
投票

在第二个示例中,您需要手动关闭文件,第一个示例中

with
上下文处理程序会为您完成此操作。

with open(strPath, "xt") as f:
    f.write("XYZ")

f = open(strPath, "r")
strReadFile = f.read()
f.close()

os.remove(strPath)

两种方式都有效。


1
投票

另一种方法是使用标准库中的 tempfile

from tempfile import TemporaryFile

with TemporaryFile() as f:
    f.write("XYZ")
    f.seek(0)
    str_read_file = f.read()

此上下文管理器关闭并删除上下文之后的临时文件。


0
投票

这里的问题是,如果文件在某个进程中打开,Windows 不会让您删除该文件(或标记为准备删除)。 Unix 类型系统将允许您执行此操作。

这里有两段代码。第一个可以在(例如)macOS 上运行。第二个将在 Windows 上运行,因此是一个跨平台兼容的变体。

import os

F = 'foo.txt'

with open(F, 'x') as foo:
    foo.write('I am Foo')

with open(F) as foo:
    print(foo.read())
    os.remove(F)

import os

F = 'foo.txt'

with open(F, 'x') as foo:
    foo.write('I am Foo')

with open(F) as foo:
    print(foo.read())

os.remove(F)
© www.soinside.com 2019 - 2024. All rights reserved.