在python中如何在打开的文件中的某些子字符串之前和之后写入?

2024-04-25 06:43:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出如何读取一个文件,找到某些子字符串,并编辑输入的文件写入字符之前和之后的子字符串,但我卡住了。我只知道如何写到文件的结尾,而不是在文件的中间某个地方的行中间!你知道吗

例如,假设我有一个文本文件:

blah blurh blap

我有密码:

f = open('inputFile.txt', 'r+')
for line in f:                          
    if 'blah' in line:
        f.write('!')
f.close()

按照上面写的方式,最后的文本会说:

blah blurh blap!

但我需要一个办法让它说:

!blah! blurh blap

我想不出来,在网上也找不到任何关于它的信息。有什么想法吗?你知道吗


Tags: 文件字符串in编辑密码地方结尾line
3条回答

一种方法,如注释中所述,是写入一个不同的临时文件,然后重命名它。你知道吗

这种方式的内存成本较低,但会占用磁盘空间的2倍。你知道吗

import os
with open('inputFile.txt', 'r') as inp, open('outfile.txt', 'w') as out:
    for line in inp:
        out.write(line.replace('blah', '!blah!'))
# Windows doesn't let you overwrite a file, remove it old input first
os.unlink('inputFile.txt')
os.rename('outfile.txt', 'inputFile.txt')

或者可以将文件完全加载到内存中,然后重新写入。你知道吗

with open('inputFile.txt', 'r') as inp:
    fixed = inp.read().replace('blah', '!blah!')
with open('inputFile.txt', 'w') as out:
    out.write(fixed)

我知道做这类事情的唯一方法是写入一个新文件,并在最后将其重命名为旧文件名。比如:

def mod_inline(myfilepath):
  tmp = os.tmpnam()
  with open(tmp,'w') as outfile:
     with open(myfilepath, 'r') as infile:
        for line in infile:
          if 'blah' in line:
            outfile.write(line + '!')
          else:
            outfile.write(line)
  os.rename(tmp, myfilepath)

输入=sample.txt

blah blub blur
test hello world

代码-读取文件,对行进行操作,输出到同一个文件

filename = 'sample.txt'

# Read the file
with open(filename) as f:
    file_lines = f.readlines()

# Operate on the lines
char = '!'
replace = 'blah'

for i,line in enumerate(file_lines):
    file_lines[i] = line.replace(replace, '{0}{1}{0}'.format(char, replace))

# Overwrite the file with the new content
with open(filename, "w") as f:
    for line in file_lines:
        f.write(line)

输出-字符串周围的字符

!blah! blub blur
test hello world

相关问题 更多 >