在 Python 中读取和覆盖文件

发布于 2024-08-24 21:55:39 字数 202 浏览 6 评论 0原文

目前我正在使用这个:

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()

但问题是旧文件比新文件大。所以我最终得到一个新文件,其末尾有旧文件的一部分。

Currently I'm using this:

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()

But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

汐鸠 2024-08-31 21:55:40

如果您不想关闭并重新打开文件,为了避免竞争条件,您可以 截断它:

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()

该功能也可能更干净、更安全 使用 open 作为上下文管理器,即使发生错误,这也会关闭文件处理程序!

with open(filename, 'r+') as f:
    text = f.read()
    text = re.sub('foobar', 'bar', text)
    f.seek(0)
    f.write(text)
    f.truncate()

If you don't want to close and reopen the file, to avoid race conditions, you could truncate it:

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()

The functionality will likely also be cleaner and safer using open as a context manager, which will close the file handler, even if an error occurs!

with open(filename, 'r+') as f:
    text = f.read()
    text = re.sub('foobar', 'bar', text)
    f.seek(0)
    f.write(text)
    f.truncate()
千里故人稀 2024-08-31 21:55:40

fileinput 模块有一个 inplace< /code> 模式,用于在不使用临时文件等的情况下将更改写入正在处理的文件。该模块很好地封装了通过透明地跟踪文件名、行的对象循环遍历文件列表中的行的常见操作如果您想在循环内检查它们,请使用数字等。

from fileinput import FileInput
for line in FileInput("file", inplace=1):
    line = line.replace("foobar", "bar")
    print(line)

The fileinput module has an inplace mode for writing changes to the file you are processing without using temporary files etc. The module nicely encapsulates the common operation of looping over the lines in a list of files, via an object which transparently keeps track of the file name, line number etc if you should want to inspect them inside the loop.

from fileinput import FileInput
for line in FileInput("file", inplace=1):
    line = line.replace("foobar", "bar")
    print(line)
゛时过境迁 2024-08-31 21:55:40

text = re.sub('foobar', 'bar', text) 之后关闭文件,重新打开它进行写入(从而清除旧内容),可能会更容易和更整洁将更新后的文本写入其中。

Probably it would be easier and neater to close the file after text = re.sub('foobar', 'bar', text), re-open it for writing (thus clearing old contents), and write your updated text to it.

柏拉图鍀咏恒 2024-08-31 21:55:40

我发现先读后写更容易记住。

例如:

with open('file') as f:
    data = f.read()
with open('file', 'w') as f:
    f.write('hello')

I find it easier to remember to just read it and then write it.

For example:

with open('file') as f:
    data = f.read()
with open('file', 'w') as f:
    f.write('hello')
因为看清所以看轻 2024-08-31 21:55:40

对于任何想要按行读取和覆盖的人,请参阅此答案。
https://stackoverflow.com/a/71285415/11442980

filename = input("Enter filename: ")
with open(filename, 'r+') as file:
    lines = file.readlines()
    file.seek(0)
    for line in lines:
        value = int(line)
        file.write(str(value + 1))
    file.truncate()

To anyone who wants to read and overwrite by line, refer to this answer.
https://stackoverflow.com/a/71285415/11442980

filename = input("Enter filename: ")
with open(filename, 'r+') as file:
    lines = file.readlines()
    file.seek(0)
    for line in lines:
        value = int(line)
        file.write(str(value + 1))
    file.truncate()
打小就很酷 2024-08-31 21:55:40

尝试将其写入新文件..

f = open(filename, 'r+')
f2= open(filename2,'a+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.close()
f2.write(text)
fw.close()

Try writing it in a new file..

f = open(filename, 'r+')
f2= open(filename2,'a+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.close()
f2.write(text)
fw.close()
可遇━不可求 2024-08-31 21:55:40

老实说,您可以看一下我构建的这个类,它执行基本的文件操作。 write 方法会覆盖并追加保留旧数据。

class IO:
    def read(self, filename):
        toRead = open(filename, "rb")

        out = toRead.read()
        toRead.close()
        
        return out
    
    def write(self, filename, data):
        toWrite = open(filename, "wb")

        out = toWrite.write(data)
        toWrite.close()

    def append(self, filename, data):
        append = self.read(filename)
        self.write(filename, append+data)
        

Honestly you can take a look at this class that I built which does basic file operations. The write method overwrites and append keeps old data.

class IO:
    def read(self, filename):
        toRead = open(filename, "rb")

        out = toRead.read()
        toRead.close()
        
        return out
    
    def write(self, filename, data):
        toWrite = open(filename, "wb")

        out = toWrite.write(data)
        toWrite.close()

    def append(self, filename, data):
        append = self.read(filename)
        self.write(filename, append+data)
        
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文