如何修改文本文件?

2024-12-12 08:40:00
admin
原创
133
摘要:问题描述:我正在使用 Python,想将字符串插入文本文件而不删除或复制文件。我该怎么做?解决方案 1:不幸的是,没有办法在不重写文件的情况下将内容插入文件中间。正如之前的发帖者所指出的,你可以使用 seek 将内容附加到文件或覆盖部分内容,但如果你想在开头或中间添加内容,则必须重写文件。这是操作系统的问题,...

问题描述:

我正在使用 Python,想将字符串插入文本文件而不删除或复制文件。我该怎么做?


解决方案 1:

不幸的是,没有办法在不重写文件的情况下将内容插入文件中间。正如之前的发帖者所指出的,你可以使用 seek 将内容附加到文件或覆盖部分内容,但如果你想在开头或中间添加内容,则必须重写文件。

这是操作系统的问题,不是 Python 的问题。所有语言都一样。

我通常会从文件中读取内容,进行修改,然后将其写入名为 myfile.txt.tmp 或类似名称的新文件。这比将整个文件读入内存要好,因为文件可能太大。临时文件完成后,我会将其重命名为与原始文件相同的名称。

这是一种很好的、​​安全的方法,因为如果文件写入由于任何原因崩溃或中止,您仍然拥有未受影响的原始文件。

解决方案 2:

取决于你想做什么。要附加,你可以用“a”打开它:

 with open("foo.txt", "a") as f:
     f.write("new line
")

如果您想要预先准备某些内容,则必须先从文件中读取:

with open("foo.txt", "r+") as f:
     old = f.read() # read everything in the file
     f.seek(0) # rewind
     f.write("new line
" + old) # write the new line before

解决方案 3:

fileinput如果使用 inplace=1 参数,Python 标准库的模块将就地重写文件:

import sys
import fileinput

# replace all occurrences of 'sit' with 'SIT' and insert a line after the 5th
for i, line in enumerate(fileinput.input('lorem_ipsum.txt', inplace=1)):
    sys.stdout.write(line.replace('sit', 'SIT'))  # replace 'sit' and write
    if i == 4: sys.stdout.write('
')  # write a blank line after the 5th line

解决方案 4:

重写文件通常是通过用修改后的名称保存旧副本来完成的。Unix 用户添加~来标记旧文件。Windows 用户会做各种各样的事情 - 添加 .bak 或 .old - 或者完全重命名文件或在名称前面加上 ~。

import shutil
shutil.move(afile, afile + "~")

destination= open(aFile, "w")
source= open(aFile + "~", "r")
for line in source:
    destination.write(line)
    if <some condition>:
        destination.write(<some additional line> + "
")

source.close()
destination.close()

除了shutil,您还可以使用以下内容。

import os
os.rename(aFile, aFile + "~")

解决方案 5:

Python 的 mmap 模块允许您插入文件。以下示例展示了如何在 Unix 中执行此操作(Windows mmap 可能有所不同)。请注意,这并不能处理所有错误情况,您可能会损坏或丢失原始文件。此外,这不会处理 unicode 字符串。

import os
from mmap import mmap

def insert(filename, str, pos):
    if len(str) < 1:
        # nothing to insert
        return

    f = open(filename, 'r+')
    m = mmap(f.fileno(), os.path.getsize(filename))
    origSize = m.size()

    # or this could be an error
    if pos > origSize:
        pos = origSize
    elif pos < 0:
        pos = 0

    m.resize(origSize + len(str))
    m[pos+len(str):] = m[pos:origSize]
    m[pos:pos+len(str)] = str
    m.close()
    f.close()

不使用 mmap 且以 'r+' 模式打开文件也可以做到这一点,但是这样做不太方便且效率较低,因为您必须读取并临时存储从插入位置到 EOF 的文件内容 - 这可能非常大。

解决方案 6:

正如 Adam 提到的那样,您必须考虑系统限制,然后才能决定是否有足够的内存将所有内容读入内存,替换部分内容并重写。

如果您正在处理小文件或没有内存问题,这可能会有所帮助:

选项 1)
将整个文件读入内存,对整行或部分行进行正则表达式替换,然后用该行加上额外的行替换它。您需要确保“中间行”在文件中是唯一的,或者如果每行都有时间戳,这应该非常可靠。

# open file with r+b (allow write and binary mode)
f = open("file.log", 'r+b')   
# read entire content of file into memory
f_content = f.read()
# basically match middle line and replace it with itself and the extra line
f_content = re.sub(r'(middle line)', r'
new line', f_content)
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content 
f.truncate()
# re-write the content with the updated content
f.write(f_content)
# close file
f.close()

选项 2)
找出中间的线,并用该线加上额外的线替换它。

# open file with r+b (allow write and binary mode)
f = open("file.log" , 'r+b')   
# get array of lines
f_content = f.readlines()
# get middle line
middle_line = len(f_content)/2
# overwrite middle line
f_content[middle_line] += "
new line"
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content 
f.truncate()
# re-write the content with the updated content
f.write(''.join(f_content))
# close file
f.close()

解决方案 7:

编写了一个小类来干净地完成此操作。

import tempfile

class FileModifierError(Exception):
    pass

class FileModifier(object):

    def __init__(self, fname):
        self.__write_dict = {}
        self.__filename = fname
        self.__tempfile = tempfile.TemporaryFile()
        with open(fname, 'rb') as fp:
            for line in fp:
                self.__tempfile.write(line)
        self.__tempfile.seek(0)

    def write(self, s, line_number = 'END'):
        if line_number != 'END' and not isinstance(line_number, (int, float)):
            raise FileModifierError("Line number %s is not a valid number" % line_number)
        try:
            self.__write_dict[line_number].append(s)
        except KeyError:
            self.__write_dict[line_number] = [s]

    def writeline(self, s, line_number = 'END'):
        self.write('%s
' % s, line_number)

    def writelines(self, s, line_number = 'END'):
        for ln in s:
            self.writeline(s, line_number)

    def __popline(self, index, fp):
        try:
            ilines = self.__write_dict.pop(index)
            for line in ilines:
                fp.write(line)
        except KeyError:
            pass

    def close(self):
        self.__exit__(None, None, None)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        with open(self.__filename,'w') as fp:
            for index, line in enumerate(self.__tempfile.readlines()):
                self.__popline(index, fp)
                fp.write(line)
            for index in sorted(self.__write_dict):
                for line in self.__write_dict[index]:
                    fp.write(line)
        self.__tempfile.close()

然后你可以这样使用它:

with FileModifier(filename) as fp:
    fp.writeline("String 1", 0)
    fp.writeline("String 2", 20)
    fp.writeline("String 3")  # To write at the end of the file

解决方案 8:

如果你了解一些unix你可以尝试以下操作:

注:$ 表示命令提示符

假设您有一个文件 my_data.txt,其内容如下:

$ cat my_data.txt
This is a data file
with all of my data in it.

然后使用该os模块,您可以使用常用sed命令

import os

# Identifiers used are:
my_data_file = "my_data.txt"
command = "sed -i 's/all/none/' my_data.txt"

# Execute the command
os.system(command)

如果您不了解 sed,请检查一下,它非常有用。

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用