简体   繁体   English

用python替换文本文件中的行。 如何?

[英]Replacing line in text file with python. How to?

I've looking for here and there how to replace multiple lines in file with new ones but my code just add a line to very end of file. 我在这里和那里一直在寻找如何用新行替换文件中的多行,但是我的代码只是在文件的末尾添加了一行。 How to replace old line with new one in proper place ? 如何在适当的地方用新的线代替旧的线?

path = /path/to/file
new_line = ''
f = open(path,'r+b')
f_content = f.readlines()
line = f_content[63]
newline = line.replace(line, new_line)
f.write(newline)
f.close()

edited: path = /path/to/file path_new = path+".tmp" new_line = "" with open(path,'r') as inf, open(path_new, 'w') as outf: for num, line in enumerate(inf): if num == 64: newline = line.replace(line, new_line) outf.write(newline) else: outf.write(line) new_file = os.rename(path_new, path) 编辑:path = / path / to / file path_new = path +“。tmp” new_line =“”,其中open(path,'r')为inf,open(path_new,'w')为outf:对于num,行枚举(inf):如果num == 64:newline = line.replace(line,new_line)outf.write(newline)else:outf.write(line)new_file = os.rename(path_new,path)

Most operating systems treat files as binary stream, so there is nothing like a line in a file. 大多数操作系统将文件视为二进制流,因此文件中没有什么像一行。 Therefore you have to rewrite the whole file, with the line substituted: 因此,您必须重写整个文件,并用以下行替换:

new_line = ''
with open(path,'r') as inf, open(path_new, 'w') as outf:
    for num, line in enumerate(inf):
        if num == 64:
           outf.write(new_line)
        else:
           outf.write(line)
os.rename(path_new, path)

In general, you have to rewrite the whole file. 通常,您必须重写整个文件。

The operating system exposes a file as a sequence of bytes. 操作系统将文件公开为字节序列。 This sequence has a so-called file pointer associated with it when you open the file. 当您打开文件时,此序列具有与其关联的所谓的文件指针 When you open the file, the pointer is at the beginning. 当您打开文件时,指针位于开头。 You can read or write bytes from this location, but you cannot insert or delete bytes. 您可以从该位置读取或写入字节,但不能插入或删除字节。 After reading or writing n bytes, the file pointer will have shifted n bytes. 读取或写入n个字节后,文件指针将移位n个字节。

Additionally Python has a method to read the whole file and split the contents into a list of lines. 此外,Python还提供了一种读取整个文件并将内容拆分为几行列表的方法。 In this case this is more convenient. 在这种情况下,这更方便。

# Read everything
with open('/path/to/file') as infile:
    data = infile.readlines()
# Replace
try:
    data[63] = 'this is the new text\n' # Do not forget the '\n'!
    with open('/path/to/file', 'w') as newfile:
        newfile.writelines(data)
except IndexError:
    print "Oops, there is no line 63!"

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

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