简体   繁体   English

在每一行的开头插入字符串

[英]Insert string at the beginning of each line

How can i insert a string at the beginning of each line in a text file, i have the following code:如何在文本文件的每一行的开头插入一个字符串,我有以下代码:

f = open('./ampo.txt', 'r+')
with open('./ampo.txt') as infile:
    for line in infile:
        f.insert(0, 'EDF ')
f.close

i get the following error:我收到以下错误:

"'file' object has no attribute 'insert'" “‘文件’对象没有‘插入’属性”

Please note that im a complete programming n00b.请注意,我是一个完整的编程 n00b。

Python comes with batteries included : Python 附带 电池

import fileinput
import sys

for line in fileinput.input(['./ampo.txt'], inplace=True):
    sys.stdout.write('EDF {l}'.format(l=line))

Unlike the solutions already posted, this also preserves file permissions.与已经发布的解决方案不同,这也保留了文件权限。

You can't modify a file inplace like that.您不能像这样就地修改文件。 Files do not support insertion.文件不支持插入。 You have to read it all in and then write it all out again.你必须把它全部读一遍,然后再写一遍。

You can do this line by line if you wish.如果您愿意,您可以逐行执行此操作。 But in that case you need to write to a temporary file and then replace the original.但在这种情况下,您需要写入一个临时文件,然后替换原来的文件。 So, for small enough files, it is just simpler to do it in one go like this:因此,对于足够小的文件,像这样一次性完成它会更简单:

with open('./ampo.txt', 'r') as f:
    lines = f.readlines()
lines = ['EDF '+line for line in lines]
with open('./ampo.txt', 'w') as f:
    f.writelines(lines)

For a file not too big:对于不太大的文件:

with open('./ampo.txt', 'rb+') as f:
    x = f.read()
    f.seek(0,0)
    f.writelines(('EDF ', x.replace('\n','\nEDF ')))
    f.truncate()

Note that , IN THEORY, in THIS case (the content is augmented), the f.truncate() may be not really necessary.请注意, f.truncate() ,在这种情况下(内容增加), f.truncate()可能不是真正必要的。 Because the with statement is supposed to close the file correctly, that is to say, writing an EOF (end of file ) at the end before closing.因为 with 语句应该正确关闭文件,也就是说,在关闭之前在末尾写入一个 EOF(文件结尾)。
That's what I observed on examples.这就是我在示例中观察到的。
But I am prudent: I think it's better to put this instruction anyway.但我很谨慎:我认为最好还是放这条指令。 For when the content diminishes, the with statement doesn't write an EOF to close correctly the file less far than the preceding initial EOF, hence trailing initial characters remains in the file.因为当内容减少时, with 语句不会写一个 EOF 来正确关闭文件,其距离小于前一个初始 EOF,因此尾随初始字符保留在文件中。
So if the with statement doens't write EOF when the content diminishes, why would it write it when the content augments ?那么如果with语句在内容减少时不写EOF,为什么当内容增加时它会写呢?

For a big file, to avoid to put all the content of the file in RAM at once:对于大文件,为了避免将文件的所有内容一次放入 RAM 中:

import os

def addsomething(filepath, ss):
    if filepath.rfind('.') > filepath.rfind(os.sep):
        a,_,c = filepath.rpartition('.')
        tempi = a + 'temp.' + c
    else:
        tempi = filepath + 'temp'

    with open(filepath, 'rb') as f, open(tempi,'wb') as g:
        g.writelines(ss + line for line in f)

    os.remove(filepath)
    os.rename(tempi,filepath)


addsomething('./ampo.txt','WZE')

Here's a solution where you write to a temporary file and move it into place.这是一个解决方案,您可以写入临时文件并将其移动到位。 You might prefer this version if the file you are rewriting is very large, since it avoids keeping the contents of the file in memory, as versions that involve .read() or .readlines() will.如果您正在重写的文件非常大,您可能更喜欢这个版本,因为它避免将文件的内容保存在内存中,因为涉及.read().readlines()版本.read() In addition, if there is any error in reading or writing, your original file will be safe:此外,如果在读取或写入时出现任何错误,您的原始文件将是安全的:

from shutil import move
from tempfile import NamedTemporaryFile

filename = './ampo.txt'
tmp = NamedTemporaryFile(delete=False)
with open(filename) as finput:
    with open(tmp.name, 'w') as ftmp:
        for line in finput:
            ftmp.write('EDF '+line)
move(tmp.name, filename)
f = open('./ampo.txt', 'r')
lines = map(lambda l : 'EDF ' + l, f.readlines())
f.close()
f = open('./ampo.txt', 'w')
map(lambda l : f.write(l), lines)
f.close()

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

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